From 33762d1ee5abd0363e2b35fbbb07cb2d38287972 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 12 Sep 2019 16:38:12 -0700 Subject: [PATCH 01/14] added support for pubcommon, digitrust, id5id --- modules/pubmaticBidAdapter.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index facecdaa578..2ec353a2f4e 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -624,10 +624,31 @@ function _handleTTDId(eids, validBidRequests) { } } +/** + * Produces external userid object in ortb 3.0 model. + */ +function _addExternalUserId(eids, value, source, atype) { + if (value) { + eids.push({ + source, + uids: [{ + id: value, + atype + }] + }); + } +} + function _handleEids(payload, validBidRequests) { let eids = []; _handleDigitrustId(eids); _handleTTDId(eids, validBidRequests); + const bidRequest = validBidRequests[0]; + if(bidRequest && bidRequest.userId){ + _addExternalUserId(eids, bidRequest.userId.pubcid, 'pubcommon', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest.userId.digitrustid, 'data.id'), 'digitru.st', 1); + _addExternalUserId(eids, bidRequest.userId.id5id, 'id5id', 1); + } if (eids.length > 0) { payload.user.eids = eids; } From 0722354d7e62dc2237e16f8b7f469557ef388a20 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 12 Sep 2019 20:11:24 -0700 Subject: [PATCH 02/14] added support for IdentityLink --- modules/pubmaticBidAdapter.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index 2ec353a2f4e..8c72367ba6e 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -644,10 +644,12 @@ function _handleEids(payload, validBidRequests) { _handleDigitrustId(eids); _handleTTDId(eids, validBidRequests); const bidRequest = validBidRequests[0]; - if(bidRequest && bidRequest.userId){ - _addExternalUserId(eids, bidRequest.userId.pubcid, 'pubcommon', 1); - _addExternalUserId(eids, utils.deepAccess(bidRequest.userId.digitrustid, 'data.id'), 'digitru.st', 1); - _addExternalUserId(eids, bidRequest.userId.id5id, 'id5id', 1); + if (bidRequest && bidRequest.userId) { + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.pubcid`), 'pubcommon', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.digitrustid.data.id`), 'digitru.st', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.id5id`), 'id5id', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.criteortus.${BIDDER_CODE}.userid`), 'criteortus', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.idl_env`), 'identity_link_envelope', 1); } if (eids.length > 0) { payload.user.eids = eids; From f2c32c07b4a4996e1e7d59510974c07d2eec7d5e Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 13 Sep 2019 10:02:20 -0700 Subject: [PATCH 03/14] changed the source for id5 --- modules/pubmaticBidAdapter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index 8c72367ba6e..c768583b96c 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -647,7 +647,7 @@ function _handleEids(payload, validBidRequests) { if (bidRequest && bidRequest.userId) { _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.pubcid`), 'pubcommon', 1); _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.digitrustid.data.id`), 'digitru.st', 1); - _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.id5id`), 'id5id', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.id5id`), 'id5-sync.com', 1); _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.criteortus.${BIDDER_CODE}.userid`), 'criteortus', 1); _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.idl_env`), 'identity_link_envelope', 1); } From eaed9874c1fc91d79118b148bbd740569e562023 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 13 Sep 2019 14:19:36 -0700 Subject: [PATCH 04/14] added unit test cases --- modules/pubmaticBidAdapter.js | 2 +- test/spec/modules/pubmaticBidAdapter_spec.js | 186 +++++++++++++++++++ 2 files changed, 187 insertions(+), 1 deletion(-) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index c768583b96c..a85a2c8e19c 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -628,7 +628,7 @@ function _handleTTDId(eids, validBidRequests) { * Produces external userid object in ortb 3.0 model. */ function _addExternalUserId(eids, value, source, atype) { - if (value) { + if (utils.isStr(value)) { eids.push({ source, uids: [{ diff --git a/test/spec/modules/pubmaticBidAdapter_spec.js b/test/spec/modules/pubmaticBidAdapter_spec.js index 3de83c56213..d0d0ce8c08b 100644 --- a/test/spec/modules/pubmaticBidAdapter_spec.js +++ b/test/spec/modules/pubmaticBidAdapter_spec.js @@ -1476,6 +1476,192 @@ describe('PubMatic adapter', function () { }); }); + describe('UserIds from request', function() { + describe('pubcommon Id', function() { + it('send the pubcommon id if it is present', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.pubcid = 'pub_common_user_id'; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.deep.equal([{ + 'source': 'pubcommon', + 'uids': [{ + 'id': 'pub_common_user_id', + 'atype': 1 + }] + }]); + }); + + it('do not pass if not string', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.pubcid = 1; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.pubcid = []; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.pubcid = null; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.pubcid = {}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + }); + }); + + describe('Digitrust Id', function() { + it('send the digitrust id if it is present', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.digitrustid = {data: {id: 'digitrust_user_id'}}; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.deep.equal([{ + 'source': 'digitru.st', + 'uids': [{ + 'id': 'digitrust_user_id', + 'atype': 1 + }] + }]); + }); + + it('do not pass if not string', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.digitrustid = {data: {id: 1}}; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.digitrustid = {data: {id: []}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.digitrustid = {data: {id: null}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.digitrustid = {data: {id: {}}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + }); + }); + + describe('ID5 Id', function() { + it('send the id5 id if it is present', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.id5id = 'id5-user-id'; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.deep.equal([{ + 'source': 'id5-sync.com', + 'uids': [{ + 'id': 'id5-user-id', + 'atype': 1 + }] + }]); + }); + + it('do not pass if not string', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.id5id = 1; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.id5id = []; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.id5id = null; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.id5id = {}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + }); + }); + + describe('CriteoRTUS Id', function() { + it('send the criteo id if it is present', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.criteortus = {pubmatic: {userid: 'criteo-rtus-user-id'}}; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.deep.equal([{ + 'source': 'criteortus', + 'uids': [{ + 'id': 'criteo-rtus-user-id', + 'atype': 1 + }] + }]); + }); + + it('do not pass if not string', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.criteortus = {appnexus: {userid: 'criteo-rtus-user-id'}}; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.criteortus = {pubmatic: {userid: 1}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.criteortus = {pubmatic: {userid: []}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.criteortus = {pubmatic: {userid: null}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.criteortus = {pubmatic: {userid: {}}}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + }); + }); + + describe('IdentityLink Id', function() { + it('send the identity-link id if it is present', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.idl_env = 'identity-link-user-id'; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.deep.equal([{ + 'source': 'identity_link_envelope', + 'uids': [{ + 'id': 'identity-link-user-id', + 'atype': 1 + }] + }]); + }); + + it('do not pass if not string', function() { + bidRequests[0].userId = {}; + bidRequests[0].userId.idl_env = 1; + let request = spec.buildRequests(bidRequests, {}); + let data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.idl_env = []; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.idl_env = null; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + bidRequests[0].userId.idl_env = {}; + request = spec.buildRequests(bidRequests, {}); + data = JSON.parse(request.data); + expect(data.user.eids).to.equal(undefined); + }); + }); + }) + it('Request params check for video ad', function () { let request = spec.buildRequests(videoBidRequests); let data = JSON.parse(request.data); From 602ee7ea83c07cf1ff83f6c000473512a9525b4c Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 16 Sep 2019 14:24:27 -0700 Subject: [PATCH 05/14] changed source param for identityLink --- modules/pubmaticBidAdapter.js | 2 +- test/spec/modules/pubmaticBidAdapter_spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index a85a2c8e19c..d1e1d072673 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -649,7 +649,7 @@ function _handleEids(payload, validBidRequests) { _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.digitrustid.data.id`), 'digitru.st', 1); _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.id5id`), 'id5-sync.com', 1); _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.criteortus.${BIDDER_CODE}.userid`), 'criteortus', 1); - _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.idl_env`), 'identity_link_envelope', 1); + _addExternalUserId(eids, utils.deepAccess(bidRequest, `userId.idl_env`), 'liveramp.com', 1); } if (eids.length > 0) { payload.user.eids = eids; diff --git a/test/spec/modules/pubmaticBidAdapter_spec.js b/test/spec/modules/pubmaticBidAdapter_spec.js index d0d0ce8c08b..ababf2dcf5f 100644 --- a/test/spec/modules/pubmaticBidAdapter_spec.js +++ b/test/spec/modules/pubmaticBidAdapter_spec.js @@ -1632,7 +1632,7 @@ describe('PubMatic adapter', function () { let request = spec.buildRequests(bidRequests, {}); let data = JSON.parse(request.data); expect(data.user.eids).to.deep.equal([{ - 'source': 'identity_link_envelope', + 'source': 'liveramp.com', 'uids': [{ 'id': 'identity-link-user-id', 'atype': 1 From bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 12:55:56 -0700 Subject: [PATCH 06/14] import utils functions as needed and not the whole module --- modules/apacdexBidAdapter.js | 32 ++++----- modules/appnexusBidAdapter.js | 118 +++++++++++++++++----------------- modules/apstreamBidAdapter.js | 10 +-- modules/asoBidAdapter.js | 60 ++++++++--------- modules/astraoneBidAdapter.js | 4 +- 5 files changed, 112 insertions(+), 112 deletions(-) diff --git a/modules/apacdexBidAdapter.js b/modules/apacdexBidAdapter.js index 6c1c350b800..421eb99b4c1 100644 --- a/modules/apacdexBidAdapter.js +++ b/modules/apacdexBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isPlainObject, isArray, replaceAuctionPrice, isFn } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'apacdex'; @@ -32,16 +32,16 @@ export const spec = { if (!bid.params.siteId && !bid.params.placementId) { return false; } - if (!utils.deepAccess(bid, 'mediaTypes.banner') && !utils.deepAccess(bid, 'mediaTypes.video')) { + if (!deepAccess(bid, 'mediaTypes.banner') && !deepAccess(bid, 'mediaTypes.video')) { return false; } - if (utils.deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video - if (!utils.deepAccess(bid, 'mediaTypes.banner.sizes')) { + if (deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video + if (!deepAccess(bid, 'mediaTypes.banner.sizes')) { // sizes at the banner is required. return false; } - } else if (utils.deepAccess(bid, 'mediaTypes.video')) { - if (!utils.deepAccess(bid, 'mediaTypes.video.playerSize')) { + } else if (deepAccess(bid, 'mediaTypes.video')) { + if (!deepAccess(bid, 'mediaTypes.video.playerSize')) { // playerSize is required for instream adUnits. return false; } @@ -170,12 +170,12 @@ export const spec = { }, interpretResponse: function (serverResponse, bidRequest) { const serverBody = serverResponse.body; - if (!serverBody || !utils.isPlainObject(serverBody)) { + if (!serverBody || !isPlainObject(serverBody)) { return []; } const serverBids = serverBody.bids; - if (!serverBids || !utils.isArray(serverBids)) { + if (!serverBids || !isArray(serverBids)) { return []; } @@ -197,12 +197,12 @@ export const spec = { bidResponse.dealId = dealId; } if (bid.vastXml) { - bidResponse.vastXml = utils.replaceAuctionPrice(bid.vastXml, bid.cpm); + bidResponse.vastXml = replaceAuctionPrice(bid.vastXml, bid.cpm); } else { - bidResponse.ad = utils.replaceAuctionPrice(bid.ad, bid.cpm); + bidResponse.ad = replaceAuctionPrice(bid.ad, bid.cpm); } bidResponse.meta = {}; - if (bid.meta && bid.meta.advertiserDomains && utils.isArray(bid.meta.advertiserDomains)) { + if (bid.meta && bid.meta.advertiserDomains && isArray(bid.meta.advertiserDomains)) { bidResponse.meta.advertiserDomains = bid.meta.advertiserDomains; } bidResponses.push(bidResponse); @@ -285,7 +285,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { if (config.getConfig('pageUrl')) { return config.getConfig('pageUrl'); } - if (utils.deepAccess(bidderRequest, 'refererInfo.referer')) { + if (deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -303,7 +303,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { * @returns {string} */ function _extractTopWindowReferrerFromBidderRequest(bidderRequest) { - if (bidderRequest && utils.deepAccess(bidderRequest, 'refererInfo.referer')) { + if (bidderRequest && deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -340,7 +340,7 @@ export function getDomain(pageUrl) { * @returns {boolean} */ export function validateGeoObject(geo) { - if (!utils.isPlainObject(geo)) { + if (!isPlainObject(geo)) { return false; } if (!geo.lat) { @@ -362,7 +362,7 @@ export function validateGeoObject(geo) { * @returns {float||null} */ function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.floorPrice) ? bid.params.floorPrice : null; } @@ -371,7 +371,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/appnexusBidAdapter.js b/modules/appnexusBidAdapter.js index 9882e71fe4f..7dcbd74d779 100644 --- a/modules/appnexusBidAdapter.js +++ b/modules/appnexusBidAdapter.js @@ -1,5 +1,5 @@ +import { convertCamelToUnderscore, isArray, isNumber, isPlainObject, logError, logInfo, deepAccess, logMessage, convertTypes, isStr, getParameterByName, deepClone, chunk, logWarn, getBidRequest, createTrackPixelHtml, isEmpty, transformBidderParamKeywords, getMaxValueFromArray, fill, getMinValueFromArray, isArrayOfNums, isFn } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder, getIabSubCategory } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO, ADPOD } from '../src/mediaTypes.js'; @@ -109,13 +109,13 @@ export const spec = { Object.keys(userObjBid.params.user) .filter(param => includes(USER_PARAMS, param)) .forEach((param) => { - let uparam = utils.convertCamelToUnderscore(param); - if (param === 'segments' && utils.isArray(userObjBid.params.user[param])) { + let uparam = convertCamelToUnderscore(param); + if (param === 'segments' && isArray(userObjBid.params.user[param])) { let segs = []; userObjBid.params.user[param].forEach(val => { - if (utils.isNumber(val)) { + if (isNumber(val)) { segs.push({'id': val}); - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { segs.push(val); } }); @@ -152,7 +152,7 @@ export const spec = { try { debugObj = JSON.parse(debugCookie); } catch (e) { - utils.logError('AppNexus Debug Auction Cookie Error:\n\n' + e); + logError('AppNexus Debug Auction Cookie Error:\n\n' + e); } } else { const debugBidRequest = find(bidRequests, hasDebug); @@ -208,7 +208,7 @@ export const spec = { if (debugObjParams.enabled) { payload.debug = debugObjParams; - utils.logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); } if (bidderRequest && bidderRequest.gdprConsent) { @@ -253,12 +253,12 @@ export const spec = { if (bidRequests[0].userId) { let eids = []; - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); + addUserId(eids, deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); + addUserId(eids, deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); if (eids.length) { payload.eids = eids; @@ -285,7 +285,7 @@ export const spec = { if (!serverResponse || serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } - utils.logError(errorMessage); + logError(errorMessage); return bids; } @@ -313,8 +313,8 @@ export const spec = { .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 .replace(/(.*)<\/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); + logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); + logMessage(debugText); } return bids; @@ -348,11 +348,11 @@ export const spec = { }, transformBidParams: function (params, isOpenRtb) { - params = utils.convertTypes({ + params = convertTypes({ 'member': 'string', 'invCode': 'string', 'placementId': 'number', - 'keywords': utils.transformBidderParamKeywords, + 'keywords': transformBidderParamKeywords, 'publisherId': 'number' }, params); @@ -365,7 +365,7 @@ export const spec = { } Object.keys(params).forEach(paramKey => { - let convertedKey = utils.convertCamelToUnderscore(paramKey); + let convertedKey = convertCamelToUnderscore(paramKey); if (convertedKey !== paramKey) { params[convertedKey] = params[paramKey]; delete params[paramKey]; @@ -388,7 +388,7 @@ export const spec = { } function isPopulatedArray(arr) { - return !!(utils.isArray(arr) && arr.length > 0); + return !!(isArray(arr) && arr.length > 0); } function deleteValues(keyPairObj) { @@ -460,9 +460,9 @@ function strIsAppnexusViewabilityScript(str) { function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) { let viewJsPayload; - if (utils.isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { + if (isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { viewJsPayload = jsTrackerArray; - } else if (utils.isArray(jsTrackerArray)) { + } else if (isArray(jsTrackerArray)) { for (let i = 0; i < jsTrackerArray.length; i++) { let currentJsTracker = jsTrackerArray[i]; if (strIsAppnexusViewabilityScript(currentJsTracker)) { @@ -486,7 +486,7 @@ function hasPurpose1Consent(bidderRequest) { let result = true; if (bidderRequest && bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { - result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -504,16 +504,16 @@ function formatRequest(payload, bidderRequest) { endpointUrl = URL_SIMPLE; } - if (utils.getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { + if (getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { options.customHeaders = { 'X-Is-Test': 1 } } if (payload.tags.length > MAX_IMPS_PER_REQUEST) { - const clonedPayload = utils.deepClone(payload); + const clonedPayload = deepClone(payload); - utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { clonedPayload.tags = tags; const payloadString = JSON.stringify(clonedPayload); request.push({ @@ -550,14 +550,14 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } renderer.setEventHandlers({ - impression: () => utils.logMessage('AppNexus outstream video impression event'), - loaded: () => utils.logMessage('AppNexus outstream video loaded event'), + impression: () => logMessage('AppNexus outstream video impression event'), + loaded: () => logMessage('AppNexus outstream video loaded event'), ended: () => { - utils.logMessage('AppNexus outstream renderer video event'); + logMessage('AppNexus outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); @@ -572,7 +572,7 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { * @return Bid */ function newBid(serverBid, rtbBid, bidderRequest) { - const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); + const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]); const bid = { requestId: serverBid.uuid, cpm: rtbBid.cpm, @@ -607,7 +607,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { ttl: 3600 }); - const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); switch (videoContext) { case ADPOD: const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id); @@ -628,7 +628,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (rtbBid.renderer_url) { const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); - const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); + const rendererOptions = deepAccess(videoBid, 'renderer.options'); bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); } break; @@ -648,7 +648,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (jsTrackers == undefined) { jsTrackers = jsTrackerDisarmed; - } else if (utils.isStr(jsTrackers)) { + } else if (isStr(jsTrackers)) { jsTrackers = [jsTrackers, jsTrackerDisarmed]; } else { jsTrackers.push(jsTrackerDisarmed); @@ -697,11 +697,11 @@ function newBid(serverBid, rtbBid, bidderRequest) { try { if (rtbBid.rtb.trackers) { const url = rtbBid.rtb.trackers[0].impression_urls[0]; - const tracker = utils.createTrackPixelHtml(url); + const tracker = createTrackPixelHtml(url); bid.ad += tracker; } } catch (error) { - utils.logError('Error appending tracking pixel', error); + logError('Error appending tracking pixel', error); } } @@ -751,8 +751,8 @@ function bidToTag(bid) { if (bid.params.externalImpId) { tag.external_imp_id = bid.params.externalImpId; } - if (!utils.isEmpty(bid.params.keywords)) { - let keywords = utils.transformBidderParamKeywords(bid.params.keywords); + if (!isEmpty(bid.params.keywords)) { + let keywords = transformBidderParamKeywords(bid.params.keywords); if (keywords.length > 0) { keywords.forEach(deleteValues); @@ -760,12 +760,12 @@ function bidToTag(bid) { tag.keywords = keywords; } - let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { tag.gpid = gpid; } - if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { + if (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`)) { tag.ad_types.push(NATIVE); if (tag.sizes.length === 0) { tag.sizes = transformSizes([1, 1]); @@ -777,8 +777,8 @@ function bidToTag(bid) { } } - const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = deepAccess(bid, 'mediaTypes.video.context'); if (videoMediaType && context === 'adpod') { tag.hb_source = 7; @@ -804,7 +804,7 @@ function bidToTag(bid) { case 'context': case 'playback_method': let type = bid.params.video[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; tag.video[param] = VIDEO_MAPPING[param][type]; break; // Deprecating tags[].video.frameworks in favor of tags[].video_frameworks @@ -815,7 +815,7 @@ function bidToTag(bid) { } }); - if (bid.params.video.frameworks && utils.isArray(bid.params.video.frameworks)) { + if (bid.params.video.frameworks && isArray(bid.params.video.frameworks)) { tag['video_frameworks'] = bid.params.video.frameworks; } } @@ -840,7 +840,7 @@ function bidToTag(bid) { case 'playbackmethod': if (typeof tag.video['playback_method'] !== 'number') { let type = videoMediaType[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; // we only support iab's options 1-4 at this time. if (type >= 1 && type <= 4) { @@ -849,7 +849,7 @@ function bidToTag(bid) { } break; case 'api': - if (!tag['video_frameworks'] && utils.isArray(videoMediaType[param])) { + if (!tag['video_frameworks'] && isArray(videoMediaType[param])) { // need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values) let apiTmp = videoMediaType[param].map(val => { let v = (val === 4) ? 5 : (val === 5) ? 4 : val; @@ -869,7 +869,7 @@ function bidToTag(bid) { tag.video = Object.assign({}, tag.video, { custom_renderer_present: true }); } - if (bid.params.frameworks && utils.isArray(bid.params.frameworks)) { + if (bid.params.frameworks && isArray(bid.params.frameworks)) { tag['banner_frameworks'] = bid.params.frameworks; } @@ -890,8 +890,8 @@ function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; - if (utils.isArray(requestSizes) && requestSizes.length === 2 && - !utils.isArray(requestSizes[0])) { + if (isArray(requestSizes) && requestSizes.length === 2 && + !isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); @@ -945,10 +945,10 @@ function hasOmidSupport(bid) { let hasOmid = false; const bidderParams = bid.params; const videoParams = bid.params.video; - if (bidderParams.frameworks && utils.isArray(bidderParams.frameworks)) { + if (bidderParams.frameworks && isArray(bidderParams.frameworks)) { hasOmid = includes(bid.params.frameworks, 6); } - if (!hasOmid && videoParams && videoParams.frameworks && utils.isArray(videoParams.frameworks)) { + if (!hasOmid && videoParams && videoParams.frameworks && isArray(videoParams.frameworks)) { hasOmid = includes(bid.params.video.frameworks, 6); } return hasOmid; @@ -963,14 +963,14 @@ function createAdPodRequest(tags, adPodBid) { const { durationRangeSec, requireExactDuration } = adPodBid.mediaTypes.video; const numberOfPlacements = getAdPodPlacementNumber(adPodBid.mediaTypes.video); - const maxDuration = utils.getMaxValueFromArray(durationRangeSec); + const maxDuration = getMaxValueFromArray(durationRangeSec); const tagToDuplicate = tags.filter(tag => tag.uuid === adPodBid.bidId); - let request = utils.fill(...tagToDuplicate, numberOfPlacements); + let request = fill(...tagToDuplicate, numberOfPlacements); if (requireExactDuration) { const divider = Math.ceil(numberOfPlacements / durationRangeSec.length); - const chunked = utils.chunk(request, divider); + const chunked = chunk(request, divider); // each configured duration is set as min/maxduration for a subset of requests durationRangeSec.forEach((duration, index) => { @@ -989,7 +989,7 @@ function createAdPodRequest(tags, adPodBid) { function getAdPodPlacementNumber(videoParams) { const { adPodDurationSec, durationRangeSec, requireExactDuration } = videoParams; - const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec); + const minAllowedDuration = getMinValueFromArray(durationRangeSec); const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration); return requireExactDuration @@ -998,7 +998,7 @@ function getAdPodPlacementNumber(videoParams) { } function setVideoProperty(tag, key, value) { - if (utils.isEmpty(tag.video)) { tag.video = {}; } + if (isEmpty(tag.video)) { tag.video = {}; } tag.video[key] = value; } @@ -1029,7 +1029,7 @@ function buildNativeRequest(params) { const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); if (isImageAsset && request[requestKey].sizes) { let sizes = request[requestKey].sizes; - if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { + if (isArrayOfNums(sizes) || (isArray(sizes) && sizes.length > 0 && sizes.every(sz => isArrayOfNums(sz)))) { request[requestKey].sizes = transformSizes(request[requestKey].sizes); } } @@ -1108,7 +1108,7 @@ function addUserId(eids, id, source, rti) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.reserve) ? bid.params.reserve : null; } @@ -1117,7 +1117,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/apstreamBidAdapter.js b/modules/apstreamBidAdapter.js index 4fb89b9c720..f2d4189f237 100644 --- a/modules/apstreamBidAdapter.js +++ b/modules/apstreamBidAdapter.js @@ -1,6 +1,6 @@ +import { generateUUID, deepAccess, createTrackPixelHtml, getDNT } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { getStorageManager } from '../src/storageManager.js'; const CONSTANTS = { @@ -221,7 +221,7 @@ var dsuModule = (function() { } function generateDsu() { - var dsuId = utils.generateUUID(); + var dsuId = generateUUID(); var loc = location(); var dsuIdSuffix = hashWithKey(dsuId + loc.toString()); @@ -303,7 +303,7 @@ function getConsentStringFromPrebid(gdprConsentConfig) { } function getIabConsentString(bidderRequest) { - if (utils.deepAccess(bidderRequest, 'gdprConsent')) { + if (deepAccess(bidderRequest, 'gdprConsent')) { return getConsentStringFromPrebid(bidderRequest.gdprConsent); } @@ -318,7 +318,7 @@ function injectPixels(ad, pixels, scripts) { let trackedAd = ad; if (pixels) { pixels.forEach(pixel => { - const tracker = utils.createTrackPixelHtml(pixel); + const tracker = createTrackPixelHtml(pixel); trackedAd += tracker; }); } @@ -420,7 +420,7 @@ function buildRequests(bidRequests, bidderRequest) { med: encodeURIComponent(window.location.href), auid: bidderRequest.auctionId, ref: document.referrer, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, sr: getScreenParams() }; diff --git a/modules/asoBidAdapter.js b/modules/asoBidAdapter.js index 8f06b8ed856..bf45b9ee48f 100644 --- a/modules/asoBidAdapter.js +++ b/modules/asoBidAdapter.js @@ -1,5 +1,5 @@ +import { _each, deepAccess, logWarn, tryAppendQueryString, inIframe, getWindowTop, parseUrl, parseSizesInput, isFn, getDNT, deepSetValue } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {Renderer} from '../src/Renderer.js'; @@ -22,16 +22,16 @@ export const spec = { buildRequests: (validBidRequests, bidderRequest) => { let serverRequests = []; - utils._each(validBidRequests, bidRequest => { + _each(validBidRequests, bidRequest => { const payload = createBasePayload(bidRequest, bidderRequest); - const bannerParams = utils.deepAccess(bidRequest, 'mediaTypes.banner'); - const videoParams = utils.deepAccess(bidRequest, 'mediaTypes.video'); + const bannerParams = deepAccess(bidRequest, 'mediaTypes.banner'); + const videoParams = deepAccess(bidRequest, 'mediaTypes.video'); let imp; if (bannerParams && videoParams) { - utils.logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') + logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') } if (bannerParams) { @@ -93,7 +93,7 @@ export const spec = { bid.ad = serverBid.adm; } else if (bid.mediaType === VIDEO) { bid.vastXml = serverBid.adm; - if (utils.deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { + if (deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { bid.adResponse = { content: bid.vastXml, }; @@ -112,25 +112,25 @@ export const spec = { if (serverResponses && serverResponses.length !== 0) { let query = ''; if (gdprConsent) { - query = utils.tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); - query = utils.tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); + query = tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); + query = tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); const consentsIds = getConsentsIds(gdprConsent); if (consentsIds) { - query = utils.tryAppendQueryString(query, 'consents', consentsIds); + query = tryAppendQueryString(query, 'consents', consentsIds); } } if (uspConsent) { - query = utils.tryAppendQueryString(query, 'us_privacy', uspConsent); + query = tryAppendQueryString(query, 'us_privacy', uspConsent); } - utils._each(serverResponses, resp => { - const userSyncs = utils.deepAccess(resp, 'body.ext.user_syncs'); + _each(serverResponses, resp => { + const userSyncs = deepAccess(resp, 'body.ext.user_syncs'); if (!userSyncs) { return; } - utils._each(userSyncs, us => { + _each(userSyncs, us => { urls.push({ type: us.type, url: us.url + (query ? '?' + query : '') @@ -159,7 +159,7 @@ function createRenderer(bid, url) { id: bid.bidId, url: url, loaded: false, - config: utils.deepAccess(bid, 'renderer.options'), + config: deepAccess(bid, 'renderer.options'), adUnitCode: bid.adUnitCode }); renderer.setRender(outstreamRender); @@ -172,16 +172,16 @@ function getUrlsInfo(bidderRequest) { const {refererInfo} = bidderRequest; - if (utils.inIframe()) { + if (inIframe()) { page = refererInfo.referer; } else { - const w = utils.getWindowTop(); + const w = getWindowTop(); page = w.location.href; referrer = w.document.referrer || ''; } page = config.getConfig('pageUrl') || page; - const url = utils.parseUrl(page); + const url = parseUrl(page); const domain = url.hostname; return { @@ -192,7 +192,7 @@ function getUrlsInfo(bidderRequest) { } function getSize(paramSizes) { - const parsedSizes = utils.parseSizesInput(paramSizes); + const parsedSizes = parseSizesInput(paramSizes); const sizes = parsedSizes.map(size => { const [width, height] = size.split('x'); const w = parseInt(width, 10); @@ -204,7 +204,7 @@ function getSize(paramSizes) { } function getBidFloor(bidRequest, size) { - if (!utils.isFn(bidRequest.getFloor)) { + if (!isFn(bidRequest.getFloor)) { return null; } @@ -245,7 +245,7 @@ function createBannerImp(bidRequest, bannerParams) { imp.banner = { w: size.w, h: size.h, - topframe: utils.inIframe() ? 0 : 1 + topframe: inIframe() ? 0 : 1 } return imp; @@ -284,7 +284,7 @@ function getEnpoint(bidRequest) { } function getConsentsIds(gdprConsent) { - const consents = utils.deepAccess(gdprConsent, 'vendorData.purpose.consents', []); + const consents = deepAccess(gdprConsent, 'vendorData.purpose.consents', []); let consentsIds = []; Object.keys(consents).forEach(function (key) { @@ -310,7 +310,7 @@ function createBasePayload(bidRequest, bidderRequest) { ref: urlsInfo.referrer }, device: { - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, h: window.innerHeight, w: window.innerWidth, }, @@ -320,29 +320,29 @@ function createBasePayload(bidRequest, bidderRequest) { }; if (bidRequest.params.attr) { - utils.deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); + deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); } if (bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); const consentsIds = getConsentsIds(bidderRequest.gdprConsent); if (consentsIds) { - utils.deepSetValue(payload, 'user.ext.consents', consentsIds); + deepSetValue(payload, 'user.ext.consents', consentsIds); } - utils.deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); + deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); } if (bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (config.getConfig('coppa')) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } - const eids = utils.deepAccess(bidRequest, 'userIdAsEids'); + const eids = deepAccess(bidRequest, 'userIdAsEids'); if (eids && eids.length) { - utils.deepSetValue(payload, 'user.ext.eids', eids); + deepSetValue(payload, 'user.ext.eids', eids); } return payload; diff --git a/modules/astraoneBidAdapter.js b/modules/astraoneBidAdapter.js index 2fec3892d27..c233e665499 100644 --- a/modules/astraoneBidAdapter.js +++ b/modules/astraoneBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js' +import { _map } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER } from '../src/mediaTypes.js' @@ -7,7 +7,7 @@ const SSP_ENDPOINT = 'https://ssp.astraone.io/auction/prebid'; const TTL = 60; function buildBidRequests(validBidRequests) { - return utils._map(validBidRequests, function(validBidRequest) { + return _map(validBidRequests, function(validBidRequest) { const params = validBidRequest.params; const bidRequest = { bidId: validBidRequest.bidId, From ef500abb06648c763caa066ccd18fd5a18f2a1b5 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 13:03:13 -0700 Subject: [PATCH 07/14] import utils functions as needed and not the whole module --- modules/atsAnalyticsAdapter.js | 22 +++++++-------- modules/audiencerunBidAdapter.js | 30 ++++++++++----------- modules/automatadBidAdapter.js | 4 +-- modules/axonixBidAdapter.js | 14 +++++----- modules/beachfrontBidAdapter.js | 46 ++++++++++++++++---------------- 5 files changed, 58 insertions(+), 58 deletions(-) diff --git a/modules/atsAnalyticsAdapter.js b/modules/atsAnalyticsAdapter.js index 0cff7bbd68f..df293556a4c 100644 --- a/modules/atsAnalyticsAdapter.js +++ b/modules/atsAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { logError, logInfo } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -256,7 +256,7 @@ export function parseBrowser() { let browserName = result && result.length ? result[0].name : ''; return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown'; } catch (err) { - utils.logError('ATS Analytics - Error while checking user browser!', err); + logError('ATS Analytics - Error while checking user browser!', err); } } @@ -265,20 +265,20 @@ function sendDataToAnalytic () { try { let dataToSend = {'Data': atsAnalyticsAdapter.context.events}; let strJSON = JSON.stringify(dataToSend); - utils.logInfo('ATS Analytics - tried to send analytics data!'); + logInfo('ATS Analytics - tried to send analytics data!'); ajax(analyticsUrl, function () { }, strJSON, {method: 'POST', contentType: 'application/json'}); } catch (err) { - utils.logError('ATS Analytics - request encounter an error: ', err); + logError('ATS Analytics - request encounter an error: ', err); } } // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { - utils.logInfo('ATS Analytics - preflight request!'); + logInfo('ATS Analytics - preflight request!'); ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { let samplingRateObject = JSON.parse(data); - utils.logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); + logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); let samplingRate = samplingRateObject['samplingRate']; setSamplingCookie(samplingRate); let samplingRateNumber = Number(samplingRate); @@ -332,7 +332,7 @@ let atsAnalyticsAdapter = Object.assign(adapter( } } } catch (err) { - utils.logError('ATS Analytics - preflight request encounter an error: ', err); + logError('ATS Analytics - preflight request encounter an error: ', err); } } } @@ -345,10 +345,10 @@ atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics; atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { if (samplingRate !== 0) { let shouldFireRequestValue = (Math.floor((Math.random() * 100 + 1)) === 100); - utils.logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); + logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); return shouldFireRequestValue; } else { - utils.logInfo('ATS Analytics - Should Fire Request: ', false); + logInfo('ATS Analytics - Should Fire Request: ', false); return false; } }; @@ -359,7 +359,7 @@ atsAnalyticsAdapter.getUserAgent = function () { // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { - utils.logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); + logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); return; } atsAnalyticsAdapter.context = { @@ -367,7 +367,7 @@ atsAnalyticsAdapter.enableAnalytics = function (config) { pid: config.options.pid }; let initOptions = config.options; - utils.logInfo('ATS Analytics - adapter enabled! '); + logInfo('ATS Analytics - adapter enabled! '); atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function }; diff --git a/modules/audiencerunBidAdapter.js b/modules/audiencerunBidAdapter.js index da0cbb39925..2c100bce27b 100644 --- a/modules/audiencerunBidAdapter.js +++ b/modules/audiencerunBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isFn, logError, getValue, getBidIdParameter, _each, isArray, triggerPixel } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -20,7 +20,7 @@ let requestedBids = []; function getPageUrl(bidderRequest) { return ( config.getConfig('pageUrl') || - utils.deepAccess(bidderRequest, 'refererInfo.referer') || + deepAccess(bidderRequest, 'refererInfo.referer') || null ); } @@ -32,8 +32,8 @@ function getPageUrl(bidderRequest) { * @returns {number} */ function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -61,8 +61,8 @@ export const spec = { */ isBidRequestValid: function (bid) { let isValid = true; - if (!utils.deepAccess(bid, 'params.zoneId')) { - utils.logError('AudienceRun zoneId parameter is required. Bid aborted.'); + if (!deepAccess(bid, 'params.zoneId')) { + logError('AudienceRun zoneId parameter is required. Bid aborted.'); isValid = false; } return isValid; @@ -77,19 +77,19 @@ export const spec = { */ buildRequests: function (bidRequests, bidderRequest) { const bids = bidRequests.map((bid) => { - const sizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes', []); + const sizes = deepAccess(bid, 'mediaTypes.banner.sizes', []); return { - zoneId: utils.getValue(bid.params, 'zoneId'), + zoneId: getValue(bid.params, 'zoneId'), sizes: sizes.map((size) => ({ w: size[0], h: size[1], })), bidfloor: getBidFloor(bid), bidId: bid.bidId, - bidderRequestId: utils.getBidIdParameter('bidderRequestId', bid), - adUnitCode: utils.getBidIdParameter('adUnitCode', bid), - auctionId: utils.getBidIdParameter('auctionId', bid), - transactionId: utils.getBidIdParameter('transactionId', bid), + bidderRequestId: getBidIdParameter('bidderRequestId', bid), + adUnitCode: getBidIdParameter('adUnitCode', bid), + auctionId: getBidIdParameter('auctionId', bid), + transactionId: getBidIdParameter('transactionId', bid), }; }); @@ -133,7 +133,7 @@ export const spec = { */ interpretResponse: function (serverResponse, bidRequest) { const bids = []; - utils._each(serverResponse.body.bid, function (bidObject) { + _each(serverResponse.body.bid, function (bidObject) { if (!bidObject.cpm || bidObject.cpm === null || !bidObject.adm) { return; } @@ -196,7 +196,7 @@ export const spec = { * @param {Array} timeoutData timeout specific data */ onTimeout: function (timeoutData) { - if (!utils.isArray(timeoutData)) { + if (!isArray(timeoutData)) { return; } @@ -204,7 +204,7 @@ export const spec = { const bidOnTimeout = requestedBids.find((requestedBid) => requestedBid.bidId === bid.bidId); if (bidOnTimeout) { - utils.triggerPixel( + triggerPixel( `${TIMEOUT_EVENT_URL}/${bidOnTimeout.zoneId}/${bidOnTimeout.bidId}` ); } diff --git a/modules/automatadBidAdapter.js b/modules/automatadBidAdapter.js index 415c52ba6d3..2cfcfbe98b4 100644 --- a/modules/automatadBidAdapter.js +++ b/modules/automatadBidAdapter.js @@ -1,5 +1,5 @@ +import { logInfo } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js' -import * as utils from '../src/utils.js' import {BANNER} from '../src/mediaTypes.js' import {ajax} from '../src/ajax.js' @@ -92,7 +92,7 @@ export const spec = { }) }) } else { - utils.logInfo('automatad :: no valid responses to interpret') + logInfo('automatad :: no valid responses to interpret') } return bidResponses diff --git a/modules/axonixBidAdapter.js b/modules/axonixBidAdapter.js index daaac27e6a4..7cd8f63bd2a 100644 --- a/modules/axonixBidAdapter.js +++ b/modules/axonixBidAdapter.js @@ -1,7 +1,7 @@ +import { isArray, logError, deepAccess, isEmpty, triggerPixel, replaceAuctionPrice } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { ajax } from '../src/ajax.js'; const BIDDER_CODE = 'axonix'; @@ -68,9 +68,9 @@ export const spec = { // video bid request validation if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('mimes') || - !utils.isArray(bid.mediaTypes[VIDEO].mimes) || + !isArray(bid.mediaTypes[VIDEO].mimes) || bid.mediaTypes[VIDEO].mimes.length === 0) { - utils.logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); + logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); return false; } @@ -142,7 +142,7 @@ export const spec = { interpretResponse: function(serverResponse) { const response = serverResponse ? serverResponse.body : []; - if (!utils.isArray(response)) { + if (!isArray(response)) { return []; } @@ -160,9 +160,9 @@ export const spec = { }, onTimeout: function(timeoutData) { - const params = utils.deepAccess(timeoutData, '0.params.0'); + const params = deepAccess(timeoutData, '0.params.0'); - if (!utils.isEmpty(params)) { + if (!isEmpty(params)) { ajax(getURL(params, 'prebid/timeout'), null, timeoutData[0], { method: 'POST', options: { @@ -177,7 +177,7 @@ export const spec = { const { nurl } = bid || {}; if (bid.nurl) { - utils.triggerPixel(utils.replaceAuctionPrice(nurl, bid.cpm)); + triggerPixel(replaceAuctionPrice(nurl, bid.cpm)); }; } } diff --git a/modules/beachfrontBidAdapter.js b/modules/beachfrontBidAdapter.js index 3531fa45d1b..a882a796851 100644 --- a/modules/beachfrontBidAdapter.js +++ b/modules/beachfrontBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, deepAccess, isArray, parseSizesInput, isFn, parseUrl, getUniqueIdentifierStr } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; @@ -34,21 +34,21 @@ export const spec = { isBidRequestValid(bid) { if (isVideoBid(bid)) { if (!getVideoBidParam(bid, 'appId')) { - utils.logWarn('Beachfront: appId param is required for video bids.'); + logWarn('Beachfront: appId param is required for video bids.'); return false; } if (!getVideoBidParam(bid, 'bidfloor')) { - utils.logWarn('Beachfront: bidfloor param is required for video bids.'); + logWarn('Beachfront: bidfloor param is required for video bids.'); return false; } } if (isBannerBid(bid)) { if (!getBannerBidParam(bid, 'appId')) { - utils.logWarn('Beachfront: appId param is required for banner bids.'); + logWarn('Beachfront: appId param is required for banner bids.'); return false; } if (!getBannerBidParam(bid, 'bidfloor')) { - utils.logWarn('Beachfront: bidfloor param is required for banner bids.'); + logWarn('Beachfront: bidfloor param is required for banner bids.'); return false; } } @@ -85,12 +85,12 @@ export const spec = { if (isVideoBid(bidRequest)) { if (!response || !response.bidPrice) { - utils.logWarn(`No valid video bids from ${spec.code} bidder`); + logWarn(`No valid video bids from ${spec.code} bidder`); return []; } let sizes = getVideoSizes(bidRequest); let firstSize = getFirstSize(sizes); - let context = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + let context = deepAccess(bidRequest, 'mediaTypes.video.context'); let responseType = getVideoBidParam(bidRequest, 'responseType') || 'both'; let responseMeta = Object.assign({ mediaType: VIDEO, advertiserDomains: [] }, response.meta); let bidResponse = { @@ -119,7 +119,7 @@ export const spec = { return bidResponse; } else { if (!response || !response.length) { - utils.logWarn(`No valid banner bids from ${spec.code} bidder`); + logWarn(`No valid banner bids from ${spec.code} bidder`); return []; } return response @@ -148,7 +148,7 @@ export const spec = { getUserSyncs(syncOptions, serverResponses = [], gdprConsent = {}, uspConsent = '') { let syncs = []; let { gdprApplies, consentString = '' } = gdprConsent; - let bannerResponse = find(serverResponses, (res) => utils.isArray(res.body)); + let bannerResponse = find(serverResponses, (res) => isArray(res.body)); if (bannerResponse) { if (syncOptions.iframeEnabled) { @@ -206,7 +206,7 @@ function getFirstSize(sizes) { } function parseSizes(sizes) { - return utils.parseSizesInput(sizes).map(size => { + return parseSizesInput(sizes).map(size => { let [ width, height ] = size.split('x'); return { w: parseInt(width, 10) || undefined, @@ -216,11 +216,11 @@ function parseSizes(sizes) { } function getVideoSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } function getBannerSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } function getOsVersion() { @@ -257,33 +257,33 @@ function getDoNotTrack() { } function isVideoBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.video'); + return deepAccess(bid, 'mediaTypes.video'); } function isBannerBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); + return deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); } function getVideoBidParam(bid, key) { - return utils.deepAccess(bid, 'params.video.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.video.' + key) || deepAccess(bid, 'params.' + key); } function getBannerBidParam(bid, key) { - return utils.deepAccess(bid, 'params.banner.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.banner.' + key) || deepAccess(bid, 'params.' + key); } function getPlayerBidParam(bid, key, defaultValue) { - let param = utils.deepAccess(bid, 'params.player.' + key); + let param = deepAccess(bid, 'params.player.' + key); return param === undefined ? defaultValue : param; } function getBannerBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; return floorInfo.floor || getBannerBidParam(bid, 'bidfloor'); } function getVideoBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; return floorInfo.floor || getVideoBidParam(bid, 'bidfloor'); } @@ -297,7 +297,7 @@ function isBannerBidValid(bid) { function getTopWindowLocation(bidderRequest) { let url = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer; - return utils.parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); + return parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); } function getTopWindowReferrer() { @@ -316,7 +316,7 @@ function getEids(bid) { function getUserId(bid) { return ({ key, source, rtiPartner, atype }) => { - let id = utils.deepAccess(bid, `userId.${key}`); + let id = deepAccess(bid, `userId.${key}`); return id ? formatEid(id, source, rtiPartner, atype) : null; }; } @@ -364,7 +364,7 @@ function createVideoRequestData(bid, bidderRequest) { isPrebid: true, appId: appId, domain: document.location.hostname, - id: utils.getUniqueIdentifierStr(), + id: getUniqueIdentifierStr(), imp: [{ video: Object.assign({ w: firstSize.w, @@ -469,7 +469,7 @@ function createBannerRequestData(bids, bidderRequest) { } SUPPORTED_USER_IDS.forEach(({ key, queryParam }) => { - let id = utils.deepAccess(bids, `0.userId.${key}`) + let id = deepAccess(bids, `0.userId.${key}`) if (id) { payload[queryParam] = id; } From 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 13:11:58 -0700 Subject: [PATCH 08/14] import utils functions as needed and not the whole module --- modules/beopBidAdapter.js | 44 +++++++++++++++++----------------- modules/bidViewabilityIO.js | 14 +++++------ modules/bidglassBidAdapter.js | 16 ++++++------- modules/bidscubeBidAdapter.js | 6 ++--- modules/bizzclickBidAdapter.js | 20 ++++++++-------- 5 files changed, 50 insertions(+), 50 deletions(-) diff --git a/modules/beopBidAdapter.js b/modules/beopBidAdapter.js index aed5d04a151..a6bc8a5687d 100644 --- a/modules/beopBidAdapter.js +++ b/modules/beopBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isArray, logWarn, triggerPixel, buildUrl, logInfo, getValue, getBidIdParameter } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'beop'; @@ -36,7 +36,7 @@ export const spec = { */ buildRequests: function(validBidRequests, bidderRequest) { const slots = validBidRequests.map(beOpRequestSlotsMaker); - let pageUrl = utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); + let pageUrl = deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || deepAccess(window, 'location.href'); let fpd = config.getLegacyFpd(config.getConfig('ortb2')); let gdpr = bidderRequest.gdprConsent; let firstSlot = slots[0]; @@ -50,7 +50,7 @@ export const spec = { kwds: (fpd && fpd.site && fpd.site.keywords) || [], dbg: false, slts: slots, - is_amp: utils.deepAccess(bidderRequest, 'referrerInfo.isAmp'), + is_amp: deepAccess(bidderRequest, 'referrerInfo.isAmp'), tc_string: (gdpr && gdpr.gdprApplies) ? gdpr.consentString : null, }; const payloadString = JSON.stringify(payloadObject); @@ -61,7 +61,7 @@ export const spec = { } }, interpretResponse: function(serverResponse, request) { - if (serverResponse && serverResponse.body && utils.isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { + if (serverResponse && serverResponse.body && isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { return serverResponse.body.bids; } return []; @@ -73,8 +73,8 @@ export const spec = { let trackingParams = buildTrackingParams(timeoutData, 'timeout', timeoutData.timeout); - utils.logWarn(BIDDER_CODE + ': timed out request'); - utils.triggerPixel(utils.buildUrl({ + logWarn(BIDDER_CODE + ': timed out request'); + triggerPixel(buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -87,8 +87,8 @@ export const spec = { } let trackingParams = buildTrackingParams(bid, 'won', bid.cpm); - utils.logInfo(BIDDER_CODE + ': won request'); - utils.triggerPixel(utils.buildUrl({ + logInfo(BIDDER_CODE + ': won request'); + triggerPixel(buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -113,8 +113,8 @@ function buildTrackingParams(data, info, value) { } function beOpRequestSlotsMaker(bid) { - const bannerSizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); - const publisherCurrency = config.getConfig('currency.adServerCurrency') || utils.getValue(bid.params, 'currency') || 'EUR'; + const bannerSizes = deepAccess(bid, 'mediaTypes.banner.sizes'); + const publisherCurrency = config.getConfig('currency.adServerCurrency') || getValue(bid.params, 'currency') || 'EUR'; let floor; if (typeof bid.getFloor === 'function') { const floorInfo = bid.getFloor({currency: publisherCurrency, mediaType: 'banner', size: [1, 1]}); @@ -123,19 +123,19 @@ function beOpRequestSlotsMaker(bid) { } } return { - sizes: utils.isArray(bannerSizes) ? bannerSizes : bid.sizes, + sizes: isArray(bannerSizes) ? bannerSizes : bid.sizes, flr: floor, - pid: utils.getValue(bid.params, 'accountId'), - nid: utils.getValue(bid.params, 'networkId'), - nptnid: utils.getValue(bid.params, 'networkPartnerId'), - bid: utils.getBidIdParameter('bidId', bid), - brid: utils.getBidIdParameter('bidderRequestId', bid), - name: utils.getBidIdParameter('adUnitCode', bid), - aid: utils.getBidIdParameter('auctionId', bid), - tid: utils.getBidIdParameter('transactionId', bid), - brc: utils.getBidIdParameter('bidRequestsCount', bid), - bdrc: utils.getBidIdParameter('bidderRequestCount', bid), - bwc: utils.getBidIdParameter('bidderWinsCount', bid), + pid: getValue(bid.params, 'accountId'), + nid: getValue(bid.params, 'networkId'), + nptnid: getValue(bid.params, 'networkPartnerId'), + bid: getBidIdParameter('bidId', bid), + brid: getBidIdParameter('bidderRequestId', bid), + name: getBidIdParameter('adUnitCode', bid), + aid: getBidIdParameter('auctionId', bid), + tid: getBidIdParameter('transactionId', bid), + brc: getBidIdParameter('bidRequestsCount', bid), + bdrc: getBidIdParameter('bidderRequestCount', bid), + bwc: getBidIdParameter('bidderWinsCount', bid), } } diff --git a/modules/bidViewabilityIO.js b/modules/bidViewabilityIO.js index 4651e424d00..d936fb4aeec 100644 --- a/modules/bidViewabilityIO.js +++ b/modules/bidViewabilityIO.js @@ -1,7 +1,7 @@ +import { logMessage } from '../src/utils.js'; import { config } from '../src/config.js'; import * as events from '../src/events.js'; import { EVENTS } from '../src/constants.json'; -import * as utils from '../src/utils.js'; const MODULE_NAME = 'bidViewabilityIO'; const CONFIG_ENABLED = 'enabled'; @@ -23,8 +23,8 @@ export let isSupportedMediaType = (bid) => { return supportedMediaTypes.indexOf(bid.mediaType) > -1; } -let logMessage = (message) => { - return utils.logMessage(`${MODULE_NAME}: ${message}`); +let _logMessage = (message) => { + return logMessage(`${MODULE_NAME}: ${message}`); } // returns options for the iO that detects if the ad is viewable @@ -43,7 +43,7 @@ export let markViewed = (bid, entry, observer) => { return () => { observer.unobserve(entry.target); events.emit(EVENTS.BID_VIEWABLE, bid); - logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); + _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); } } @@ -59,13 +59,13 @@ export let viewCallbackFactory = (bid) => { return (entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { - logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + _logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); entry.target.view_tracker = setTimeout(markViewed(bid, entry, observer), IAB_VIEWABLE_DISPLAY_TIME); } else { - logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); + _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); if (entry.target.view_tracker) { clearTimeout(entry.target.view_tracker); - logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + _logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); } } }); diff --git a/modules/bidglassBidAdapter.js b/modules/bidglassBidAdapter.js index b77ca474e13..3184372881b 100644 --- a/modules/bidglassBidAdapter.js +++ b/modules/bidglassBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { _each, isArray, getBidIdParameter, deepClone, getUniqueIdentifierStr } from '../src/utils.js'; // import {config} from 'src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; @@ -69,12 +69,12 @@ export const spec = { let bidglass = window['bidglass']; - utils._each(validBidRequests, function(bid) { - bid.sizes = ((utils.isArray(bid.sizes) && utils.isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); - bid.sizes = bid.sizes.filter(size => utils.isArray(size)); + _each(validBidRequests, function(bid) { + bid.sizes = ((isArray(bid.sizes) && isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); + bid.sizes = bid.sizes.filter(size => isArray(size)); - var adUnitId = utils.getBidIdParameter('adUnitId', bid.params); - var options = utils.deepClone(bid.params); + var adUnitId = getBidIdParameter('adUnitId', bid.params); + var options = deepClone(bid.params); delete options.adUnitId; @@ -96,7 +96,7 @@ export const spec = { // Stuff to send: page URL const bidReq = { - reqId: utils.getUniqueIdentifierStr(), + reqId: getUniqueIdentifierStr(), imps: imps, ref: getReferer(), ori: getOrigins() @@ -125,7 +125,7 @@ export const spec = { interpretResponse: function(serverResponse) { const bidResponses = []; - utils._each(serverResponse.body.bidResponses, function(serverBid) { + _each(serverResponse.body.bidResponses, function(serverBid) { const bidResponse = { requestId: serverBid.requestId, cpm: parseFloat(serverBid.cpm), diff --git a/modules/bidscubeBidAdapter.js b/modules/bidscubeBidAdapter.js index d3f27a5ac6d..951bd97d255 100644 --- a/modules/bidscubeBidAdapter.js +++ b/modules/bidscubeBidAdapter.js @@ -1,6 +1,6 @@ +import { logMessage, getWindowLocation } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js' -import * as utils from '../src/utils.js' const BIDDER_CODE = 'bidscube' const URL = 'https://supply.bidscube.com/?c=o&m=multi' @@ -20,9 +20,9 @@ export const spec = { try { window.top.location.toString() winTop = window.top - } catch (e) { utils.logMessage(e) } + } catch (e) { logMessage(e) } - const location = utils.getWindowLocation() + const location = getWindowLocation() const placements = [] for (let i = 0; i < validBidRequests.length; i++) { diff --git a/modules/bizzclickBidAdapter.js b/modules/bizzclickBidAdapter.js index 95c53b78de2..38195f8f9d9 100644 --- a/modules/bizzclickBidAdapter.js +++ b/modules/bizzclickBidAdapter.js @@ -1,6 +1,6 @@ +import { logMessage, getDNT, deepSetValue, deepAccess, _map, logWarn } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; const BIDDER_CODE = 'bizzclick'; const ACCOUNTID_MACROS = '[account_id]'; @@ -67,7 +67,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; let bids = []; for (let bidRequest of validBidRequests) { @@ -80,7 +80,7 @@ export const spec = { device: { w: winTop.screen.width, h: winTop.screen.height, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '', }, site: { @@ -124,12 +124,12 @@ export const spec = { } if (bidRequest) { if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) { - utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); - utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); + deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); + deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); } if (bidRequest.uspConsent !== undefined) { - utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); + deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); } } bids.push(data) @@ -194,7 +194,7 @@ export const spec = { * @returns {boolean} */ const checkRequestType = (bidRequest, type) => { - return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); + return (typeof deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); } const parseNative = admObject => { const { assets, link, imptrackers, jstracker } = admObject.native; @@ -240,7 +240,7 @@ const addNativeParameters = bidRequest => { id: bidRequest.transactionId, ver: NATIVE_VERSION, }; - const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { + const assets = _map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, @@ -286,7 +286,7 @@ const parseSizes = (bid, mediaType) => { mediaTypes.video.w, mediaTypes.video.h ]; - } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { + } else if (Array.isArray(deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; @@ -299,7 +299,7 @@ const parseSizes = (bid, mediaType) => { } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = bid.sizes } else { - utils.logWarn('no sizes are setup or found'); + logWarn('no sizes are setup or found'); } return sizes } From 0a32ede82f3f19f22e8696fd03dd735eae758dbf Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 13:19:31 -0700 Subject: [PATCH 09/14] Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. --- modules/apacdexBidAdapter.js | 32 ++++----- modules/appnexusBidAdapter.js | 118 +++++++++++++++++----------------- modules/apstreamBidAdapter.js | 10 +-- modules/asoBidAdapter.js | 60 ++++++++--------- modules/astraoneBidAdapter.js | 4 +- 5 files changed, 112 insertions(+), 112 deletions(-) diff --git a/modules/apacdexBidAdapter.js b/modules/apacdexBidAdapter.js index 421eb99b4c1..6c1c350b800 100644 --- a/modules/apacdexBidAdapter.js +++ b/modules/apacdexBidAdapter.js @@ -1,4 +1,4 @@ -import { deepAccess, isPlainObject, isArray, replaceAuctionPrice, isFn } from '../src/utils.js'; +import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'apacdex'; @@ -32,16 +32,16 @@ export const spec = { if (!bid.params.siteId && !bid.params.placementId) { return false; } - if (!deepAccess(bid, 'mediaTypes.banner') && !deepAccess(bid, 'mediaTypes.video')) { + if (!utils.deepAccess(bid, 'mediaTypes.banner') && !utils.deepAccess(bid, 'mediaTypes.video')) { return false; } - if (deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video - if (!deepAccess(bid, 'mediaTypes.banner.sizes')) { + if (utils.deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video + if (!utils.deepAccess(bid, 'mediaTypes.banner.sizes')) { // sizes at the banner is required. return false; } - } else if (deepAccess(bid, 'mediaTypes.video')) { - if (!deepAccess(bid, 'mediaTypes.video.playerSize')) { + } else if (utils.deepAccess(bid, 'mediaTypes.video')) { + if (!utils.deepAccess(bid, 'mediaTypes.video.playerSize')) { // playerSize is required for instream adUnits. return false; } @@ -170,12 +170,12 @@ export const spec = { }, interpretResponse: function (serverResponse, bidRequest) { const serverBody = serverResponse.body; - if (!serverBody || !isPlainObject(serverBody)) { + if (!serverBody || !utils.isPlainObject(serverBody)) { return []; } const serverBids = serverBody.bids; - if (!serverBids || !isArray(serverBids)) { + if (!serverBids || !utils.isArray(serverBids)) { return []; } @@ -197,12 +197,12 @@ export const spec = { bidResponse.dealId = dealId; } if (bid.vastXml) { - bidResponse.vastXml = replaceAuctionPrice(bid.vastXml, bid.cpm); + bidResponse.vastXml = utils.replaceAuctionPrice(bid.vastXml, bid.cpm); } else { - bidResponse.ad = replaceAuctionPrice(bid.ad, bid.cpm); + bidResponse.ad = utils.replaceAuctionPrice(bid.ad, bid.cpm); } bidResponse.meta = {}; - if (bid.meta && bid.meta.advertiserDomains && isArray(bid.meta.advertiserDomains)) { + if (bid.meta && bid.meta.advertiserDomains && utils.isArray(bid.meta.advertiserDomains)) { bidResponse.meta.advertiserDomains = bid.meta.advertiserDomains; } bidResponses.push(bidResponse); @@ -285,7 +285,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { if (config.getConfig('pageUrl')) { return config.getConfig('pageUrl'); } - if (deepAccess(bidderRequest, 'refererInfo.referer')) { + if (utils.deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -303,7 +303,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { * @returns {string} */ function _extractTopWindowReferrerFromBidderRequest(bidderRequest) { - if (bidderRequest && deepAccess(bidderRequest, 'refererInfo.referer')) { + if (bidderRequest && utils.deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -340,7 +340,7 @@ export function getDomain(pageUrl) { * @returns {boolean} */ export function validateGeoObject(geo) { - if (!isPlainObject(geo)) { + if (!utils.isPlainObject(geo)) { return false; } if (!geo.lat) { @@ -362,7 +362,7 @@ export function validateGeoObject(geo) { * @returns {float||null} */ function getBidFloor(bid) { - if (!isFn(bid.getFloor)) { + if (!utils.isFn(bid.getFloor)) { return (bid.params.floorPrice) ? bid.params.floorPrice : null; } @@ -371,7 +371,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/appnexusBidAdapter.js b/modules/appnexusBidAdapter.js index 7dcbd74d779..9882e71fe4f 100644 --- a/modules/appnexusBidAdapter.js +++ b/modules/appnexusBidAdapter.js @@ -1,5 +1,5 @@ -import { convertCamelToUnderscore, isArray, isNumber, isPlainObject, logError, logInfo, deepAccess, logMessage, convertTypes, isStr, getParameterByName, deepClone, chunk, logWarn, getBidRequest, createTrackPixelHtml, isEmpty, transformBidderParamKeywords, getMaxValueFromArray, fill, getMinValueFromArray, isArrayOfNums, isFn } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; +import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder, getIabSubCategory } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO, ADPOD } from '../src/mediaTypes.js'; @@ -109,13 +109,13 @@ export const spec = { Object.keys(userObjBid.params.user) .filter(param => includes(USER_PARAMS, param)) .forEach((param) => { - let uparam = convertCamelToUnderscore(param); - if (param === 'segments' && isArray(userObjBid.params.user[param])) { + let uparam = utils.convertCamelToUnderscore(param); + if (param === 'segments' && utils.isArray(userObjBid.params.user[param])) { let segs = []; userObjBid.params.user[param].forEach(val => { - if (isNumber(val)) { + if (utils.isNumber(val)) { segs.push({'id': val}); - } else if (isPlainObject(val)) { + } else if (utils.isPlainObject(val)) { segs.push(val); } }); @@ -152,7 +152,7 @@ export const spec = { try { debugObj = JSON.parse(debugCookie); } catch (e) { - logError('AppNexus Debug Auction Cookie Error:\n\n' + e); + utils.logError('AppNexus Debug Auction Cookie Error:\n\n' + e); } } else { const debugBidRequest = find(bidRequests, hasDebug); @@ -208,7 +208,7 @@ export const spec = { if (debugObjParams.enabled) { payload.debug = debugObjParams; - logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + utils.logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); } if (bidderRequest && bidderRequest.gdprConsent) { @@ -253,12 +253,12 @@ export const spec = { if (bidRequests[0].userId) { let eids = []; - addUserId(eids, deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); - addUserId(eids, deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); - addUserId(eids, deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); - addUserId(eids, deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); - addUserId(eids, deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); - addUserId(eids, deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); + addUserId(eids, utils.deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); if (eids.length) { payload.eids = eids; @@ -285,7 +285,7 @@ export const spec = { if (!serverResponse || serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } - logError(errorMessage); + utils.logError(errorMessage); return bids; } @@ -313,8 +313,8 @@ export const spec = { .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 .replace(/(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags - logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); - logMessage(debugText); + utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); + utils.logMessage(debugText); } return bids; @@ -348,11 +348,11 @@ export const spec = { }, transformBidParams: function (params, isOpenRtb) { - params = convertTypes({ + params = utils.convertTypes({ 'member': 'string', 'invCode': 'string', 'placementId': 'number', - 'keywords': transformBidderParamKeywords, + 'keywords': utils.transformBidderParamKeywords, 'publisherId': 'number' }, params); @@ -365,7 +365,7 @@ export const spec = { } Object.keys(params).forEach(paramKey => { - let convertedKey = convertCamelToUnderscore(paramKey); + let convertedKey = utils.convertCamelToUnderscore(paramKey); if (convertedKey !== paramKey) { params[convertedKey] = params[paramKey]; delete params[paramKey]; @@ -388,7 +388,7 @@ export const spec = { } function isPopulatedArray(arr) { - return !!(isArray(arr) && arr.length > 0); + return !!(utils.isArray(arr) && arr.length > 0); } function deleteValues(keyPairObj) { @@ -460,9 +460,9 @@ function strIsAppnexusViewabilityScript(str) { function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) { let viewJsPayload; - if (isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { + if (utils.isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { viewJsPayload = jsTrackerArray; - } else if (isArray(jsTrackerArray)) { + } else if (utils.isArray(jsTrackerArray)) { for (let i = 0; i < jsTrackerArray.length; i++) { let currentJsTracker = jsTrackerArray[i]; if (strIsAppnexusViewabilityScript(currentJsTracker)) { @@ -486,7 +486,7 @@ function hasPurpose1Consent(bidderRequest) { let result = true; if (bidderRequest && bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { - result = !!(deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -504,16 +504,16 @@ function formatRequest(payload, bidderRequest) { endpointUrl = URL_SIMPLE; } - if (getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { + if (utils.getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { options.customHeaders = { 'X-Is-Test': 1 } } if (payload.tags.length > MAX_IMPS_PER_REQUEST) { - const clonedPayload = deepClone(payload); + const clonedPayload = utils.deepClone(payload); - chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { clonedPayload.tags = tags; const payloadString = JSON.stringify(clonedPayload); request.push({ @@ -550,14 +550,14 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - logWarn('Prebid Error calling setRender on renderer', err); + utils.logWarn('Prebid Error calling setRender on renderer', err); } renderer.setEventHandlers({ - impression: () => logMessage('AppNexus outstream video impression event'), - loaded: () => logMessage('AppNexus outstream video loaded event'), + impression: () => utils.logMessage('AppNexus outstream video impression event'), + loaded: () => utils.logMessage('AppNexus outstream video loaded event'), ended: () => { - logMessage('AppNexus outstream renderer video event'); + utils.logMessage('AppNexus outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); @@ -572,7 +572,7 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { * @return Bid */ function newBid(serverBid, rtbBid, bidderRequest) { - const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]); + const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); const bid = { requestId: serverBid.uuid, cpm: rtbBid.cpm, @@ -607,7 +607,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { ttl: 3600 }); - const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); switch (videoContext) { case ADPOD: const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id); @@ -628,7 +628,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (rtbBid.renderer_url) { const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); - const rendererOptions = deepAccess(videoBid, 'renderer.options'); + const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); } break; @@ -648,7 +648,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (jsTrackers == undefined) { jsTrackers = jsTrackerDisarmed; - } else if (isStr(jsTrackers)) { + } else if (utils.isStr(jsTrackers)) { jsTrackers = [jsTrackers, jsTrackerDisarmed]; } else { jsTrackers.push(jsTrackerDisarmed); @@ -697,11 +697,11 @@ function newBid(serverBid, rtbBid, bidderRequest) { try { if (rtbBid.rtb.trackers) { const url = rtbBid.rtb.trackers[0].impression_urls[0]; - const tracker = createTrackPixelHtml(url); + const tracker = utils.createTrackPixelHtml(url); bid.ad += tracker; } } catch (error) { - logError('Error appending tracking pixel', error); + utils.logError('Error appending tracking pixel', error); } } @@ -751,8 +751,8 @@ function bidToTag(bid) { if (bid.params.externalImpId) { tag.external_imp_id = bid.params.externalImpId; } - if (!isEmpty(bid.params.keywords)) { - let keywords = transformBidderParamKeywords(bid.params.keywords); + if (!utils.isEmpty(bid.params.keywords)) { + let keywords = utils.transformBidderParamKeywords(bid.params.keywords); if (keywords.length > 0) { keywords.forEach(deleteValues); @@ -760,12 +760,12 @@ function bidToTag(bid) { tag.keywords = keywords; } - let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { tag.gpid = gpid; } - if (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`)) { + if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { tag.ad_types.push(NATIVE); if (tag.sizes.length === 0) { tag.sizes = transformSizes([1, 1]); @@ -777,8 +777,8 @@ function bidToTag(bid) { } } - const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`); - const context = deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = utils.deepAccess(bid, 'mediaTypes.video.context'); if (videoMediaType && context === 'adpod') { tag.hb_source = 7; @@ -804,7 +804,7 @@ function bidToTag(bid) { case 'context': case 'playback_method': let type = bid.params.video[param]; - type = (isArray(type)) ? type[0] : type; + type = (utils.isArray(type)) ? type[0] : type; tag.video[param] = VIDEO_MAPPING[param][type]; break; // Deprecating tags[].video.frameworks in favor of tags[].video_frameworks @@ -815,7 +815,7 @@ function bidToTag(bid) { } }); - if (bid.params.video.frameworks && isArray(bid.params.video.frameworks)) { + if (bid.params.video.frameworks && utils.isArray(bid.params.video.frameworks)) { tag['video_frameworks'] = bid.params.video.frameworks; } } @@ -840,7 +840,7 @@ function bidToTag(bid) { case 'playbackmethod': if (typeof tag.video['playback_method'] !== 'number') { let type = videoMediaType[param]; - type = (isArray(type)) ? type[0] : type; + type = (utils.isArray(type)) ? type[0] : type; // we only support iab's options 1-4 at this time. if (type >= 1 && type <= 4) { @@ -849,7 +849,7 @@ function bidToTag(bid) { } break; case 'api': - if (!tag['video_frameworks'] && isArray(videoMediaType[param])) { + if (!tag['video_frameworks'] && utils.isArray(videoMediaType[param])) { // need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values) let apiTmp = videoMediaType[param].map(val => { let v = (val === 4) ? 5 : (val === 5) ? 4 : val; @@ -869,7 +869,7 @@ function bidToTag(bid) { tag.video = Object.assign({}, tag.video, { custom_renderer_present: true }); } - if (bid.params.frameworks && isArray(bid.params.frameworks)) { + if (bid.params.frameworks && utils.isArray(bid.params.frameworks)) { tag['banner_frameworks'] = bid.params.frameworks; } @@ -890,8 +890,8 @@ function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; - if (isArray(requestSizes) && requestSizes.length === 2 && - !isArray(requestSizes[0])) { + if (utils.isArray(requestSizes) && requestSizes.length === 2 && + !utils.isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); @@ -945,10 +945,10 @@ function hasOmidSupport(bid) { let hasOmid = false; const bidderParams = bid.params; const videoParams = bid.params.video; - if (bidderParams.frameworks && isArray(bidderParams.frameworks)) { + if (bidderParams.frameworks && utils.isArray(bidderParams.frameworks)) { hasOmid = includes(bid.params.frameworks, 6); } - if (!hasOmid && videoParams && videoParams.frameworks && isArray(videoParams.frameworks)) { + if (!hasOmid && videoParams && videoParams.frameworks && utils.isArray(videoParams.frameworks)) { hasOmid = includes(bid.params.video.frameworks, 6); } return hasOmid; @@ -963,14 +963,14 @@ function createAdPodRequest(tags, adPodBid) { const { durationRangeSec, requireExactDuration } = adPodBid.mediaTypes.video; const numberOfPlacements = getAdPodPlacementNumber(adPodBid.mediaTypes.video); - const maxDuration = getMaxValueFromArray(durationRangeSec); + const maxDuration = utils.getMaxValueFromArray(durationRangeSec); const tagToDuplicate = tags.filter(tag => tag.uuid === adPodBid.bidId); - let request = fill(...tagToDuplicate, numberOfPlacements); + let request = utils.fill(...tagToDuplicate, numberOfPlacements); if (requireExactDuration) { const divider = Math.ceil(numberOfPlacements / durationRangeSec.length); - const chunked = chunk(request, divider); + const chunked = utils.chunk(request, divider); // each configured duration is set as min/maxduration for a subset of requests durationRangeSec.forEach((duration, index) => { @@ -989,7 +989,7 @@ function createAdPodRequest(tags, adPodBid) { function getAdPodPlacementNumber(videoParams) { const { adPodDurationSec, durationRangeSec, requireExactDuration } = videoParams; - const minAllowedDuration = getMinValueFromArray(durationRangeSec); + const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec); const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration); return requireExactDuration @@ -998,7 +998,7 @@ function getAdPodPlacementNumber(videoParams) { } function setVideoProperty(tag, key, value) { - if (isEmpty(tag.video)) { tag.video = {}; } + if (utils.isEmpty(tag.video)) { tag.video = {}; } tag.video[key] = value; } @@ -1029,7 +1029,7 @@ function buildNativeRequest(params) { const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); if (isImageAsset && request[requestKey].sizes) { let sizes = request[requestKey].sizes; - if (isArrayOfNums(sizes) || (isArray(sizes) && sizes.length > 0 && sizes.every(sz => isArrayOfNums(sz)))) { + if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { request[requestKey].sizes = transformSizes(request[requestKey].sizes); } } @@ -1108,7 +1108,7 @@ function addUserId(eids, id, source, rti) { } function getBidFloor(bid) { - if (!isFn(bid.getFloor)) { + if (!utils.isFn(bid.getFloor)) { return (bid.params.reserve) ? bid.params.reserve : null; } @@ -1117,7 +1117,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/apstreamBidAdapter.js b/modules/apstreamBidAdapter.js index f2d4189f237..4fb89b9c720 100644 --- a/modules/apstreamBidAdapter.js +++ b/modules/apstreamBidAdapter.js @@ -1,6 +1,6 @@ -import { generateUUID, deepAccess, createTrackPixelHtml, getDNT } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; +import * as utils from '../src/utils.js'; import { getStorageManager } from '../src/storageManager.js'; const CONSTANTS = { @@ -221,7 +221,7 @@ var dsuModule = (function() { } function generateDsu() { - var dsuId = generateUUID(); + var dsuId = utils.generateUUID(); var loc = location(); var dsuIdSuffix = hashWithKey(dsuId + loc.toString()); @@ -303,7 +303,7 @@ function getConsentStringFromPrebid(gdprConsentConfig) { } function getIabConsentString(bidderRequest) { - if (deepAccess(bidderRequest, 'gdprConsent')) { + if (utils.deepAccess(bidderRequest, 'gdprConsent')) { return getConsentStringFromPrebid(bidderRequest.gdprConsent); } @@ -318,7 +318,7 @@ function injectPixels(ad, pixels, scripts) { let trackedAd = ad; if (pixels) { pixels.forEach(pixel => { - const tracker = createTrackPixelHtml(pixel); + const tracker = utils.createTrackPixelHtml(pixel); trackedAd += tracker; }); } @@ -420,7 +420,7 @@ function buildRequests(bidRequests, bidderRequest) { med: encodeURIComponent(window.location.href), auid: bidderRequest.auctionId, ref: document.referrer, - dnt: getDNT() ? 1 : 0, + dnt: utils.getDNT() ? 1 : 0, sr: getScreenParams() }; diff --git a/modules/asoBidAdapter.js b/modules/asoBidAdapter.js index bf45b9ee48f..8f06b8ed856 100644 --- a/modules/asoBidAdapter.js +++ b/modules/asoBidAdapter.js @@ -1,5 +1,5 @@ -import { _each, deepAccess, logWarn, tryAppendQueryString, inIframe, getWindowTop, parseUrl, parseSizesInput, isFn, getDNT, deepSetValue } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; +import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {Renderer} from '../src/Renderer.js'; @@ -22,16 +22,16 @@ export const spec = { buildRequests: (validBidRequests, bidderRequest) => { let serverRequests = []; - _each(validBidRequests, bidRequest => { + utils._each(validBidRequests, bidRequest => { const payload = createBasePayload(bidRequest, bidderRequest); - const bannerParams = deepAccess(bidRequest, 'mediaTypes.banner'); - const videoParams = deepAccess(bidRequest, 'mediaTypes.video'); + const bannerParams = utils.deepAccess(bidRequest, 'mediaTypes.banner'); + const videoParams = utils.deepAccess(bidRequest, 'mediaTypes.video'); let imp; if (bannerParams && videoParams) { - logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') + utils.logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') } if (bannerParams) { @@ -93,7 +93,7 @@ export const spec = { bid.ad = serverBid.adm; } else if (bid.mediaType === VIDEO) { bid.vastXml = serverBid.adm; - if (deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { + if (utils.deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { bid.adResponse = { content: bid.vastXml, }; @@ -112,25 +112,25 @@ export const spec = { if (serverResponses && serverResponses.length !== 0) { let query = ''; if (gdprConsent) { - query = tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); - query = tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); + query = utils.tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); + query = utils.tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); const consentsIds = getConsentsIds(gdprConsent); if (consentsIds) { - query = tryAppendQueryString(query, 'consents', consentsIds); + query = utils.tryAppendQueryString(query, 'consents', consentsIds); } } if (uspConsent) { - query = tryAppendQueryString(query, 'us_privacy', uspConsent); + query = utils.tryAppendQueryString(query, 'us_privacy', uspConsent); } - _each(serverResponses, resp => { - const userSyncs = deepAccess(resp, 'body.ext.user_syncs'); + utils._each(serverResponses, resp => { + const userSyncs = utils.deepAccess(resp, 'body.ext.user_syncs'); if (!userSyncs) { return; } - _each(userSyncs, us => { + utils._each(userSyncs, us => { urls.push({ type: us.type, url: us.url + (query ? '?' + query : '') @@ -159,7 +159,7 @@ function createRenderer(bid, url) { id: bid.bidId, url: url, loaded: false, - config: deepAccess(bid, 'renderer.options'), + config: utils.deepAccess(bid, 'renderer.options'), adUnitCode: bid.adUnitCode }); renderer.setRender(outstreamRender); @@ -172,16 +172,16 @@ function getUrlsInfo(bidderRequest) { const {refererInfo} = bidderRequest; - if (inIframe()) { + if (utils.inIframe()) { page = refererInfo.referer; } else { - const w = getWindowTop(); + const w = utils.getWindowTop(); page = w.location.href; referrer = w.document.referrer || ''; } page = config.getConfig('pageUrl') || page; - const url = parseUrl(page); + const url = utils.parseUrl(page); const domain = url.hostname; return { @@ -192,7 +192,7 @@ function getUrlsInfo(bidderRequest) { } function getSize(paramSizes) { - const parsedSizes = parseSizesInput(paramSizes); + const parsedSizes = utils.parseSizesInput(paramSizes); const sizes = parsedSizes.map(size => { const [width, height] = size.split('x'); const w = parseInt(width, 10); @@ -204,7 +204,7 @@ function getSize(paramSizes) { } function getBidFloor(bidRequest, size) { - if (!isFn(bidRequest.getFloor)) { + if (!utils.isFn(bidRequest.getFloor)) { return null; } @@ -245,7 +245,7 @@ function createBannerImp(bidRequest, bannerParams) { imp.banner = { w: size.w, h: size.h, - topframe: inIframe() ? 0 : 1 + topframe: utils.inIframe() ? 0 : 1 } return imp; @@ -284,7 +284,7 @@ function getEnpoint(bidRequest) { } function getConsentsIds(gdprConsent) { - const consents = deepAccess(gdprConsent, 'vendorData.purpose.consents', []); + const consents = utils.deepAccess(gdprConsent, 'vendorData.purpose.consents', []); let consentsIds = []; Object.keys(consents).forEach(function (key) { @@ -310,7 +310,7 @@ function createBasePayload(bidRequest, bidderRequest) { ref: urlsInfo.referrer }, device: { - dnt: getDNT() ? 1 : 0, + dnt: utils.getDNT() ? 1 : 0, h: window.innerHeight, w: window.innerWidth, }, @@ -320,29 +320,29 @@ function createBasePayload(bidRequest, bidderRequest) { }; if (bidRequest.params.attr) { - deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); + utils.deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); } if (bidderRequest.gdprConsent) { - deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); const consentsIds = getConsentsIds(bidderRequest.gdprConsent); if (consentsIds) { - deepSetValue(payload, 'user.ext.consents', consentsIds); + utils.deepSetValue(payload, 'user.ext.consents', consentsIds); } - deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); + utils.deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); } if (bidderRequest.uspConsent) { - deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (config.getConfig('coppa')) { - deepSetValue(payload, 'regs.coppa', 1); + utils.deepSetValue(payload, 'regs.coppa', 1); } - const eids = deepAccess(bidRequest, 'userIdAsEids'); + const eids = utils.deepAccess(bidRequest, 'userIdAsEids'); if (eids && eids.length) { - deepSetValue(payload, 'user.ext.eids', eids); + utils.deepSetValue(payload, 'user.ext.eids', eids); } return payload; diff --git a/modules/astraoneBidAdapter.js b/modules/astraoneBidAdapter.js index c233e665499..2fec3892d27 100644 --- a/modules/astraoneBidAdapter.js +++ b/modules/astraoneBidAdapter.js @@ -1,4 +1,4 @@ -import { _map } from '../src/utils.js'; +import * as utils from '../src/utils.js' import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER } from '../src/mediaTypes.js' @@ -7,7 +7,7 @@ const SSP_ENDPOINT = 'https://ssp.astraone.io/auction/prebid'; const TTL = 60; function buildBidRequests(validBidRequests) { - return _map(validBidRequests, function(validBidRequest) { + return utils._map(validBidRequests, function(validBidRequest) { const params = validBidRequest.params; const bidRequest = { bidId: validBidRequest.bidId, From e4dc4955c78551d746a257cc59189d6f7df69538 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 13:19:35 -0700 Subject: [PATCH 10/14] Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. --- modules/atsAnalyticsAdapter.js | 22 +++++++-------- modules/audiencerunBidAdapter.js | 30 ++++++++++----------- modules/automatadBidAdapter.js | 4 +-- modules/axonixBidAdapter.js | 14 +++++----- modules/beachfrontBidAdapter.js | 46 ++++++++++++++++---------------- 5 files changed, 58 insertions(+), 58 deletions(-) diff --git a/modules/atsAnalyticsAdapter.js b/modules/atsAnalyticsAdapter.js index df293556a4c..0cff7bbd68f 100644 --- a/modules/atsAnalyticsAdapter.js +++ b/modules/atsAnalyticsAdapter.js @@ -1,7 +1,7 @@ -import { logError, logInfo } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; +import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -256,7 +256,7 @@ export function parseBrowser() { let browserName = result && result.length ? result[0].name : ''; return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown'; } catch (err) { - logError('ATS Analytics - Error while checking user browser!', err); + utils.logError('ATS Analytics - Error while checking user browser!', err); } } @@ -265,20 +265,20 @@ function sendDataToAnalytic () { try { let dataToSend = {'Data': atsAnalyticsAdapter.context.events}; let strJSON = JSON.stringify(dataToSend); - logInfo('ATS Analytics - tried to send analytics data!'); + utils.logInfo('ATS Analytics - tried to send analytics data!'); ajax(analyticsUrl, function () { }, strJSON, {method: 'POST', contentType: 'application/json'}); } catch (err) { - logError('ATS Analytics - request encounter an error: ', err); + utils.logError('ATS Analytics - request encounter an error: ', err); } } // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { - logInfo('ATS Analytics - preflight request!'); + utils.logInfo('ATS Analytics - preflight request!'); ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { let samplingRateObject = JSON.parse(data); - logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); + utils.logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); let samplingRate = samplingRateObject['samplingRate']; setSamplingCookie(samplingRate); let samplingRateNumber = Number(samplingRate); @@ -332,7 +332,7 @@ let atsAnalyticsAdapter = Object.assign(adapter( } } } catch (err) { - logError('ATS Analytics - preflight request encounter an error: ', err); + utils.logError('ATS Analytics - preflight request encounter an error: ', err); } } } @@ -345,10 +345,10 @@ atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics; atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { if (samplingRate !== 0) { let shouldFireRequestValue = (Math.floor((Math.random() * 100 + 1)) === 100); - logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); + utils.logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); return shouldFireRequestValue; } else { - logInfo('ATS Analytics - Should Fire Request: ', false); + utils.logInfo('ATS Analytics - Should Fire Request: ', false); return false; } }; @@ -359,7 +359,7 @@ atsAnalyticsAdapter.getUserAgent = function () { // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { - logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); + utils.logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); return; } atsAnalyticsAdapter.context = { @@ -367,7 +367,7 @@ atsAnalyticsAdapter.enableAnalytics = function (config) { pid: config.options.pid }; let initOptions = config.options; - logInfo('ATS Analytics - adapter enabled! '); + utils.logInfo('ATS Analytics - adapter enabled! '); atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function }; diff --git a/modules/audiencerunBidAdapter.js b/modules/audiencerunBidAdapter.js index 2c100bce27b..da0cbb39925 100644 --- a/modules/audiencerunBidAdapter.js +++ b/modules/audiencerunBidAdapter.js @@ -1,4 +1,4 @@ -import { deepAccess, isFn, logError, getValue, getBidIdParameter, _each, isArray, triggerPixel } from '../src/utils.js'; +import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -20,7 +20,7 @@ let requestedBids = []; function getPageUrl(bidderRequest) { return ( config.getConfig('pageUrl') || - deepAccess(bidderRequest, 'refererInfo.referer') || + utils.deepAccess(bidderRequest, 'refererInfo.referer') || null ); } @@ -32,8 +32,8 @@ function getPageUrl(bidderRequest) { * @returns {number} */ function getBidFloor(bid) { - if (!isFn(bid.getFloor)) { - return deepAccess(bid, 'params.bidfloor', 0); + if (!utils.isFn(bid.getFloor)) { + return utils.deepAccess(bid, 'params.bidfloor', 0); } try { @@ -61,8 +61,8 @@ export const spec = { */ isBidRequestValid: function (bid) { let isValid = true; - if (!deepAccess(bid, 'params.zoneId')) { - logError('AudienceRun zoneId parameter is required. Bid aborted.'); + if (!utils.deepAccess(bid, 'params.zoneId')) { + utils.logError('AudienceRun zoneId parameter is required. Bid aborted.'); isValid = false; } return isValid; @@ -77,19 +77,19 @@ export const spec = { */ buildRequests: function (bidRequests, bidderRequest) { const bids = bidRequests.map((bid) => { - const sizes = deepAccess(bid, 'mediaTypes.banner.sizes', []); + const sizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes', []); return { - zoneId: getValue(bid.params, 'zoneId'), + zoneId: utils.getValue(bid.params, 'zoneId'), sizes: sizes.map((size) => ({ w: size[0], h: size[1], })), bidfloor: getBidFloor(bid), bidId: bid.bidId, - bidderRequestId: getBidIdParameter('bidderRequestId', bid), - adUnitCode: getBidIdParameter('adUnitCode', bid), - auctionId: getBidIdParameter('auctionId', bid), - transactionId: getBidIdParameter('transactionId', bid), + bidderRequestId: utils.getBidIdParameter('bidderRequestId', bid), + adUnitCode: utils.getBidIdParameter('adUnitCode', bid), + auctionId: utils.getBidIdParameter('auctionId', bid), + transactionId: utils.getBidIdParameter('transactionId', bid), }; }); @@ -133,7 +133,7 @@ export const spec = { */ interpretResponse: function (serverResponse, bidRequest) { const bids = []; - _each(serverResponse.body.bid, function (bidObject) { + utils._each(serverResponse.body.bid, function (bidObject) { if (!bidObject.cpm || bidObject.cpm === null || !bidObject.adm) { return; } @@ -196,7 +196,7 @@ export const spec = { * @param {Array} timeoutData timeout specific data */ onTimeout: function (timeoutData) { - if (!isArray(timeoutData)) { + if (!utils.isArray(timeoutData)) { return; } @@ -204,7 +204,7 @@ export const spec = { const bidOnTimeout = requestedBids.find((requestedBid) => requestedBid.bidId === bid.bidId); if (bidOnTimeout) { - triggerPixel( + utils.triggerPixel( `${TIMEOUT_EVENT_URL}/${bidOnTimeout.zoneId}/${bidOnTimeout.bidId}` ); } diff --git a/modules/automatadBidAdapter.js b/modules/automatadBidAdapter.js index 2cfcfbe98b4..415c52ba6d3 100644 --- a/modules/automatadBidAdapter.js +++ b/modules/automatadBidAdapter.js @@ -1,5 +1,5 @@ -import { logInfo } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js' +import * as utils from '../src/utils.js' import {BANNER} from '../src/mediaTypes.js' import {ajax} from '../src/ajax.js' @@ -92,7 +92,7 @@ export const spec = { }) }) } else { - logInfo('automatad :: no valid responses to interpret') + utils.logInfo('automatad :: no valid responses to interpret') } return bidResponses diff --git a/modules/axonixBidAdapter.js b/modules/axonixBidAdapter.js index 7cd8f63bd2a..daaac27e6a4 100644 --- a/modules/axonixBidAdapter.js +++ b/modules/axonixBidAdapter.js @@ -1,7 +1,7 @@ -import { isArray, logError, deepAccess, isEmpty, triggerPixel, replaceAuctionPrice } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; +import * as utils from '../src/utils.js'; import { ajax } from '../src/ajax.js'; const BIDDER_CODE = 'axonix'; @@ -68,9 +68,9 @@ export const spec = { // video bid request validation if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('mimes') || - !isArray(bid.mediaTypes[VIDEO].mimes) || + !utils.isArray(bid.mediaTypes[VIDEO].mimes) || bid.mediaTypes[VIDEO].mimes.length === 0) { - logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); + utils.logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); return false; } @@ -142,7 +142,7 @@ export const spec = { interpretResponse: function(serverResponse) { const response = serverResponse ? serverResponse.body : []; - if (!isArray(response)) { + if (!utils.isArray(response)) { return []; } @@ -160,9 +160,9 @@ export const spec = { }, onTimeout: function(timeoutData) { - const params = deepAccess(timeoutData, '0.params.0'); + const params = utils.deepAccess(timeoutData, '0.params.0'); - if (!isEmpty(params)) { + if (!utils.isEmpty(params)) { ajax(getURL(params, 'prebid/timeout'), null, timeoutData[0], { method: 'POST', options: { @@ -177,7 +177,7 @@ export const spec = { const { nurl } = bid || {}; if (bid.nurl) { - triggerPixel(replaceAuctionPrice(nurl, bid.cpm)); + utils.triggerPixel(utils.replaceAuctionPrice(nurl, bid.cpm)); }; } } diff --git a/modules/beachfrontBidAdapter.js b/modules/beachfrontBidAdapter.js index a882a796851..3531fa45d1b 100644 --- a/modules/beachfrontBidAdapter.js +++ b/modules/beachfrontBidAdapter.js @@ -1,4 +1,4 @@ -import { logWarn, deepAccess, isArray, parseSizesInput, isFn, parseUrl, getUniqueIdentifierStr } from '../src/utils.js'; +import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; @@ -34,21 +34,21 @@ export const spec = { isBidRequestValid(bid) { if (isVideoBid(bid)) { if (!getVideoBidParam(bid, 'appId')) { - logWarn('Beachfront: appId param is required for video bids.'); + utils.logWarn('Beachfront: appId param is required for video bids.'); return false; } if (!getVideoBidParam(bid, 'bidfloor')) { - logWarn('Beachfront: bidfloor param is required for video bids.'); + utils.logWarn('Beachfront: bidfloor param is required for video bids.'); return false; } } if (isBannerBid(bid)) { if (!getBannerBidParam(bid, 'appId')) { - logWarn('Beachfront: appId param is required for banner bids.'); + utils.logWarn('Beachfront: appId param is required for banner bids.'); return false; } if (!getBannerBidParam(bid, 'bidfloor')) { - logWarn('Beachfront: bidfloor param is required for banner bids.'); + utils.logWarn('Beachfront: bidfloor param is required for banner bids.'); return false; } } @@ -85,12 +85,12 @@ export const spec = { if (isVideoBid(bidRequest)) { if (!response || !response.bidPrice) { - logWarn(`No valid video bids from ${spec.code} bidder`); + utils.logWarn(`No valid video bids from ${spec.code} bidder`); return []; } let sizes = getVideoSizes(bidRequest); let firstSize = getFirstSize(sizes); - let context = deepAccess(bidRequest, 'mediaTypes.video.context'); + let context = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); let responseType = getVideoBidParam(bidRequest, 'responseType') || 'both'; let responseMeta = Object.assign({ mediaType: VIDEO, advertiserDomains: [] }, response.meta); let bidResponse = { @@ -119,7 +119,7 @@ export const spec = { return bidResponse; } else { if (!response || !response.length) { - logWarn(`No valid banner bids from ${spec.code} bidder`); + utils.logWarn(`No valid banner bids from ${spec.code} bidder`); return []; } return response @@ -148,7 +148,7 @@ export const spec = { getUserSyncs(syncOptions, serverResponses = [], gdprConsent = {}, uspConsent = '') { let syncs = []; let { gdprApplies, consentString = '' } = gdprConsent; - let bannerResponse = find(serverResponses, (res) => isArray(res.body)); + let bannerResponse = find(serverResponses, (res) => utils.isArray(res.body)); if (bannerResponse) { if (syncOptions.iframeEnabled) { @@ -206,7 +206,7 @@ function getFirstSize(sizes) { } function parseSizes(sizes) { - return parseSizesInput(sizes).map(size => { + return utils.parseSizesInput(sizes).map(size => { let [ width, height ] = size.split('x'); return { w: parseInt(width, 10) || undefined, @@ -216,11 +216,11 @@ function parseSizes(sizes) { } function getVideoSizes(bid) { - return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } function getBannerSizes(bid) { - return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } function getOsVersion() { @@ -257,33 +257,33 @@ function getDoNotTrack() { } function isVideoBid(bid) { - return deepAccess(bid, 'mediaTypes.video'); + return utils.deepAccess(bid, 'mediaTypes.video'); } function isBannerBid(bid) { - return deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); + return utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); } function getVideoBidParam(bid, key) { - return deepAccess(bid, 'params.video.' + key) || deepAccess(bid, 'params.' + key); + return utils.deepAccess(bid, 'params.video.' + key) || utils.deepAccess(bid, 'params.' + key); } function getBannerBidParam(bid, key) { - return deepAccess(bid, 'params.banner.' + key) || deepAccess(bid, 'params.' + key); + return utils.deepAccess(bid, 'params.banner.' + key) || utils.deepAccess(bid, 'params.' + key); } function getPlayerBidParam(bid, key, defaultValue) { - let param = deepAccess(bid, 'params.player.' + key); + let param = utils.deepAccess(bid, 'params.player.' + key); return param === undefined ? defaultValue : param; } function getBannerBidFloor(bid) { - let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; + let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; return floorInfo.floor || getBannerBidParam(bid, 'bidfloor'); } function getVideoBidFloor(bid) { - let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; + let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; return floorInfo.floor || getVideoBidParam(bid, 'bidfloor'); } @@ -297,7 +297,7 @@ function isBannerBidValid(bid) { function getTopWindowLocation(bidderRequest) { let url = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer; - return parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); + return utils.parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); } function getTopWindowReferrer() { @@ -316,7 +316,7 @@ function getEids(bid) { function getUserId(bid) { return ({ key, source, rtiPartner, atype }) => { - let id = deepAccess(bid, `userId.${key}`); + let id = utils.deepAccess(bid, `userId.${key}`); return id ? formatEid(id, source, rtiPartner, atype) : null; }; } @@ -364,7 +364,7 @@ function createVideoRequestData(bid, bidderRequest) { isPrebid: true, appId: appId, domain: document.location.hostname, - id: getUniqueIdentifierStr(), + id: utils.getUniqueIdentifierStr(), imp: [{ video: Object.assign({ w: firstSize.w, @@ -469,7 +469,7 @@ function createBannerRequestData(bids, bidderRequest) { } SUPPORTED_USER_IDS.forEach(({ key, queryParam }) => { - let id = deepAccess(bids, `0.userId.${key}`) + let id = utils.deepAccess(bids, `0.userId.${key}`) if (id) { payload[queryParam] = id; } From 9e42ba5700bce0aca28084ff1b41a747bdb9e2d1 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Fri, 24 Sep 2021 13:19:40 -0700 Subject: [PATCH 11/14] Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. --- modules/beopBidAdapter.js | 44 +++++++++++++++++----------------- modules/bidViewabilityIO.js | 14 +++++------ modules/bidglassBidAdapter.js | 16 ++++++------- modules/bidscubeBidAdapter.js | 6 ++--- modules/bizzclickBidAdapter.js | 20 ++++++++-------- 5 files changed, 50 insertions(+), 50 deletions(-) diff --git a/modules/beopBidAdapter.js b/modules/beopBidAdapter.js index a6bc8a5687d..aed5d04a151 100644 --- a/modules/beopBidAdapter.js +++ b/modules/beopBidAdapter.js @@ -1,4 +1,4 @@ -import { deepAccess, isArray, logWarn, triggerPixel, buildUrl, logInfo, getValue, getBidIdParameter } from '../src/utils.js'; +import * as utils from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'beop'; @@ -36,7 +36,7 @@ export const spec = { */ buildRequests: function(validBidRequests, bidderRequest) { const slots = validBidRequests.map(beOpRequestSlotsMaker); - let pageUrl = deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || deepAccess(window, 'location.href'); + let pageUrl = utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); let fpd = config.getLegacyFpd(config.getConfig('ortb2')); let gdpr = bidderRequest.gdprConsent; let firstSlot = slots[0]; @@ -50,7 +50,7 @@ export const spec = { kwds: (fpd && fpd.site && fpd.site.keywords) || [], dbg: false, slts: slots, - is_amp: deepAccess(bidderRequest, 'referrerInfo.isAmp'), + is_amp: utils.deepAccess(bidderRequest, 'referrerInfo.isAmp'), tc_string: (gdpr && gdpr.gdprApplies) ? gdpr.consentString : null, }; const payloadString = JSON.stringify(payloadObject); @@ -61,7 +61,7 @@ export const spec = { } }, interpretResponse: function(serverResponse, request) { - if (serverResponse && serverResponse.body && isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { + if (serverResponse && serverResponse.body && utils.isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { return serverResponse.body.bids; } return []; @@ -73,8 +73,8 @@ export const spec = { let trackingParams = buildTrackingParams(timeoutData, 'timeout', timeoutData.timeout); - logWarn(BIDDER_CODE + ': timed out request'); - triggerPixel(buildUrl({ + utils.logWarn(BIDDER_CODE + ': timed out request'); + utils.triggerPixel(utils.buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -87,8 +87,8 @@ export const spec = { } let trackingParams = buildTrackingParams(bid, 'won', bid.cpm); - logInfo(BIDDER_CODE + ': won request'); - triggerPixel(buildUrl({ + utils.logInfo(BIDDER_CODE + ': won request'); + utils.triggerPixel(utils.buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -113,8 +113,8 @@ function buildTrackingParams(data, info, value) { } function beOpRequestSlotsMaker(bid) { - const bannerSizes = deepAccess(bid, 'mediaTypes.banner.sizes'); - const publisherCurrency = config.getConfig('currency.adServerCurrency') || getValue(bid.params, 'currency') || 'EUR'; + const bannerSizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); + const publisherCurrency = config.getConfig('currency.adServerCurrency') || utils.getValue(bid.params, 'currency') || 'EUR'; let floor; if (typeof bid.getFloor === 'function') { const floorInfo = bid.getFloor({currency: publisherCurrency, mediaType: 'banner', size: [1, 1]}); @@ -123,19 +123,19 @@ function beOpRequestSlotsMaker(bid) { } } return { - sizes: isArray(bannerSizes) ? bannerSizes : bid.sizes, + sizes: utils.isArray(bannerSizes) ? bannerSizes : bid.sizes, flr: floor, - pid: getValue(bid.params, 'accountId'), - nid: getValue(bid.params, 'networkId'), - nptnid: getValue(bid.params, 'networkPartnerId'), - bid: getBidIdParameter('bidId', bid), - brid: getBidIdParameter('bidderRequestId', bid), - name: getBidIdParameter('adUnitCode', bid), - aid: getBidIdParameter('auctionId', bid), - tid: getBidIdParameter('transactionId', bid), - brc: getBidIdParameter('bidRequestsCount', bid), - bdrc: getBidIdParameter('bidderRequestCount', bid), - bwc: getBidIdParameter('bidderWinsCount', bid), + pid: utils.getValue(bid.params, 'accountId'), + nid: utils.getValue(bid.params, 'networkId'), + nptnid: utils.getValue(bid.params, 'networkPartnerId'), + bid: utils.getBidIdParameter('bidId', bid), + brid: utils.getBidIdParameter('bidderRequestId', bid), + name: utils.getBidIdParameter('adUnitCode', bid), + aid: utils.getBidIdParameter('auctionId', bid), + tid: utils.getBidIdParameter('transactionId', bid), + brc: utils.getBidIdParameter('bidRequestsCount', bid), + bdrc: utils.getBidIdParameter('bidderRequestCount', bid), + bwc: utils.getBidIdParameter('bidderWinsCount', bid), } } diff --git a/modules/bidViewabilityIO.js b/modules/bidViewabilityIO.js index d936fb4aeec..4651e424d00 100644 --- a/modules/bidViewabilityIO.js +++ b/modules/bidViewabilityIO.js @@ -1,7 +1,7 @@ -import { logMessage } from '../src/utils.js'; import { config } from '../src/config.js'; import * as events from '../src/events.js'; import { EVENTS } from '../src/constants.json'; +import * as utils from '../src/utils.js'; const MODULE_NAME = 'bidViewabilityIO'; const CONFIG_ENABLED = 'enabled'; @@ -23,8 +23,8 @@ export let isSupportedMediaType = (bid) => { return supportedMediaTypes.indexOf(bid.mediaType) > -1; } -let _logMessage = (message) => { - return logMessage(`${MODULE_NAME}: ${message}`); +let logMessage = (message) => { + return utils.logMessage(`${MODULE_NAME}: ${message}`); } // returns options for the iO that detects if the ad is viewable @@ -43,7 +43,7 @@ export let markViewed = (bid, entry, observer) => { return () => { observer.unobserve(entry.target); events.emit(EVENTS.BID_VIEWABLE, bid); - _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); + logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); } } @@ -59,13 +59,13 @@ export let viewCallbackFactory = (bid) => { return (entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { - _logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); entry.target.view_tracker = setTimeout(markViewed(bid, entry, observer), IAB_VIEWABLE_DISPLAY_TIME); } else { - _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); + logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); if (entry.target.view_tracker) { clearTimeout(entry.target.view_tracker); - _logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); } } }); diff --git a/modules/bidglassBidAdapter.js b/modules/bidglassBidAdapter.js index 3184372881b..b77ca474e13 100644 --- a/modules/bidglassBidAdapter.js +++ b/modules/bidglassBidAdapter.js @@ -1,4 +1,4 @@ -import { _each, isArray, getBidIdParameter, deepClone, getUniqueIdentifierStr } from '../src/utils.js'; +import * as utils from '../src/utils.js'; // import {config} from 'src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; @@ -69,12 +69,12 @@ export const spec = { let bidglass = window['bidglass']; - _each(validBidRequests, function(bid) { - bid.sizes = ((isArray(bid.sizes) && isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); - bid.sizes = bid.sizes.filter(size => isArray(size)); + utils._each(validBidRequests, function(bid) { + bid.sizes = ((utils.isArray(bid.sizes) && utils.isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); + bid.sizes = bid.sizes.filter(size => utils.isArray(size)); - var adUnitId = getBidIdParameter('adUnitId', bid.params); - var options = deepClone(bid.params); + var adUnitId = utils.getBidIdParameter('adUnitId', bid.params); + var options = utils.deepClone(bid.params); delete options.adUnitId; @@ -96,7 +96,7 @@ export const spec = { // Stuff to send: page URL const bidReq = { - reqId: getUniqueIdentifierStr(), + reqId: utils.getUniqueIdentifierStr(), imps: imps, ref: getReferer(), ori: getOrigins() @@ -125,7 +125,7 @@ export const spec = { interpretResponse: function(serverResponse) { const bidResponses = []; - _each(serverResponse.body.bidResponses, function(serverBid) { + utils._each(serverResponse.body.bidResponses, function(serverBid) { const bidResponse = { requestId: serverBid.requestId, cpm: parseFloat(serverBid.cpm), diff --git a/modules/bidscubeBidAdapter.js b/modules/bidscubeBidAdapter.js index 951bd97d255..d3f27a5ac6d 100644 --- a/modules/bidscubeBidAdapter.js +++ b/modules/bidscubeBidAdapter.js @@ -1,6 +1,6 @@ -import { logMessage, getWindowLocation } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js' +import * as utils from '../src/utils.js' const BIDDER_CODE = 'bidscube' const URL = 'https://supply.bidscube.com/?c=o&m=multi' @@ -20,9 +20,9 @@ export const spec = { try { window.top.location.toString() winTop = window.top - } catch (e) { logMessage(e) } + } catch (e) { utils.logMessage(e) } - const location = getWindowLocation() + const location = utils.getWindowLocation() const placements = [] for (let i = 0; i < validBidRequests.length; i++) { diff --git a/modules/bizzclickBidAdapter.js b/modules/bizzclickBidAdapter.js index 38195f8f9d9..95c53b78de2 100644 --- a/modules/bizzclickBidAdapter.js +++ b/modules/bizzclickBidAdapter.js @@ -1,6 +1,6 @@ -import { logMessage, getDNT, deepSetValue, deepAccess, _map, logWarn } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; +import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; const BIDDER_CODE = 'bizzclick'; const ACCOUNTID_MACROS = '[account_id]'; @@ -67,7 +67,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - logMessage(e); + utils.logMessage(e); }; let bids = []; for (let bidRequest of validBidRequests) { @@ -80,7 +80,7 @@ export const spec = { device: { w: winTop.screen.width, h: winTop.screen.height, - dnt: getDNT() ? 1 : 0, + dnt: utils.getDNT() ? 1 : 0, language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '', }, site: { @@ -124,12 +124,12 @@ export const spec = { } if (bidRequest) { if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) { - deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); - deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); + utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); + utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); } if (bidRequest.uspConsent !== undefined) { - deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); + utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); } } bids.push(data) @@ -194,7 +194,7 @@ export const spec = { * @returns {boolean} */ const checkRequestType = (bidRequest, type) => { - return (typeof deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); + return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); } const parseNative = admObject => { const { assets, link, imptrackers, jstracker } = admObject.native; @@ -240,7 +240,7 @@ const addNativeParameters = bidRequest => { id: bidRequest.transactionId, ver: NATIVE_VERSION, }; - const assets = _map(bidRequest.mediaTypes.native, (bidParams, key) => { + const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, @@ -286,7 +286,7 @@ const parseSizes = (bid, mediaType) => { mediaTypes.video.w, mediaTypes.video.h ]; - } else if (Array.isArray(deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { + } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; @@ -299,7 +299,7 @@ const parseSizes = (bid, mediaType) => { } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = bid.sizes } else { - logWarn('no sizes are setup or found'); + utils.logWarn('no sizes are setup or found'); } return sizes } From f43b61d49513c7526f9522af8548dc4d1674d388 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 08:48:40 -0700 Subject: [PATCH 12/14] import utils functions as needed and not the whole module --- modules/realvuAnalyticsAdapter.js | 12 ++--- modules/reconciliationRtdProvider.js | 12 ++--- modules/relaidoBidAdapter.js | 72 ++++++++++++++-------------- modules/resetdigitalBidAdapter.js | 7 ++- modules/revcontentBidAdapter.js | 18 +++---- 5 files changed, 59 insertions(+), 62 deletions(-) diff --git a/modules/realvuAnalyticsAdapter.js b/modules/realvuAnalyticsAdapter.js index 5540d136dea..832e907893c 100644 --- a/modules/realvuAnalyticsAdapter.js +++ b/modules/realvuAnalyticsAdapter.js @@ -3,11 +3,9 @@ import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; import { getStorageManager } from '../src/storageManager.js'; - +import { logMessage, logError } from '../src/utils.js'; const storage = getStorageManager(); -const utils = require('../src/utils.js'); - let realvuAnalyticsAdapter = adapter({ global: 'realvuAnalytics', handler: 'on', @@ -401,7 +399,7 @@ export let lib = { // @if NODE_ENV='debug' let now = new Date(); let msg = (now.getTime() - time0) / 1000 + ' RENDERED ' + a.unit_id; - utils.logMessage(msg); + logMessage(msg); // @endif let rpt = z.bids_rpt(a, true); z.track(a, 'rend', rpt); @@ -885,7 +883,7 @@ realvuAnalyticsAdapter.originEnableAnalytics = realvuAnalyticsAdapter.enableAnal realvuAnalyticsAdapter.enableAnalytics = function (config) { _options = config.options; if (typeof (_options.partnerId) == 'undefined' || _options.partnerId == '') { - utils.logError('Missed realvu.com partnerId parameter', 101, 'Missed partnerId parameter'); + logError('Missed realvu.com partnerId parameter', 101, 'Missed partnerId parameter'); } realvuAnalyticsAdapter.originEnableAnalytics(config); return _options.partnerId; @@ -905,7 +903,7 @@ realvuAnalyticsAdapter.track = function ({eventType, args}) { ' creativei_id=' + args.creative_id; } // msg += '\nargs=' + JSON.stringify(args) + '
'; - utils.logMessage(msg); + logMessage(msg); // @endif const boost = window.top1.realvu_aa; @@ -935,7 +933,7 @@ realvuAnalyticsAdapter.track = function ({eventType, args}) { realvuAnalyticsAdapter.checkIn = function (bid, partnerId) { // find (or add if not registered yet) the unit in boost if (typeof (partnerId) == 'undefined' || partnerId == '') { - utils.logError('Missed realvu.com partnerId parameter', 102, 'Missed partnerId parameter'); + logError('Missed realvu.com partnerId parameter', 102, 'Missed partnerId parameter'); } let a = window.top1.realvu_aa.check({ unit_id: bid.adUnitCode, diff --git a/modules/reconciliationRtdProvider.js b/modules/reconciliationRtdProvider.js index f8636862d4c..fc5f0ab621a 100644 --- a/modules/reconciliationRtdProvider.js +++ b/modules/reconciliationRtdProvider.js @@ -18,7 +18,7 @@ import { submodule } from '../src/hook.js'; import { ajaxBuilder } from '../src/ajax.js'; -import * as utils from '../src/utils.js'; +import { isGptPubadsDefined, timestamp, generateUUID, logError } from '../src/utils.js'; import find from 'core-js-pure/features/array/find.js'; /** @type {Object} */ @@ -52,7 +52,7 @@ function handleAdMessage(e) { } if (data.type === MessageType.IMPRESSION_REQUEST) { - if (utils.isGptPubadsDefined()) { + if (isGptPubadsDefined()) { // 1. Find the last iframed window before window.top where the tracker was injected // (the tracker could be injected in nested iframes) const adWin = getTopIFrameWin(e.source); @@ -65,7 +65,7 @@ function handleAdMessage(e) { adDeliveryId = adSlot.getTargeting('RSDK_ADID'); adDeliveryId = adDeliveryId.length ? adDeliveryId[0] - : `${utils.timestamp()}-${utils.generateUUID()}`; + : `${timestamp()}-${generateUUID()}`; } } } @@ -136,7 +136,7 @@ export function getTopIFrameWin(win, topWin) { * @return {Object[]} slot GoogleTag slots */ function getAllSlots() { - return utils.isGptPubadsDefined() && window.googletag.pubads().getSlots(); + return isGptPubadsDefined() && window.googletag.pubads().getSlots(); } /** @@ -246,7 +246,7 @@ function getReconciliationData(adUnitsCodes) { const adSlot = getSlotByCode(adUnitCode); const adUnitId = adSlot ? adSlot.getAdUnitPath() : adUnitCode; - const adDeliveryId = `${utils.timestamp()}-${utils.generateUUID()}`; + const adDeliveryId = `${timestamp()}-${generateUUID()}`; dataToReturn[adUnitCode] = { RSDK_AUID: adUnitId, @@ -287,7 +287,7 @@ function init(moduleConfig) { _moduleParams = Object.assign({}, DEFAULT_PARAMS, params); initListeners(); } else { - utils.logError('missing params for Reconciliation provider'); + logError('missing params for Reconciliation provider'); } return true; } diff --git a/modules/relaidoBidAdapter.js b/modules/relaidoBidAdapter.js index 14effa263a3..4df13b52a39 100644 --- a/modules/relaidoBidAdapter.js +++ b/modules/relaidoBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, logWarn, getBidIdParameter, parseQueryStringParameters, triggerPixel, generateUUID, isArray } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { Renderer } from '../src/Renderer.js'; @@ -13,19 +13,19 @@ const UUID_KEY = 'relaido_uuid'; const storage = getStorageManager(); function isBidRequestValid(bid) { - if (!utils.deepAccess(bid, 'params.placementId')) { - utils.logWarn('placementId param is reqeuired.'); + if (!deepAccess(bid, 'params.placementId')) { + logWarn('placementId param is reqeuired.'); return false; } if (hasVideoMediaType(bid) && isVideoValid(bid)) { return true; } else { - utils.logWarn('Invalid mediaType video.'); + logWarn('Invalid mediaType video.'); } if (hasBannerMediaType(bid) && isBannerValid(bid)) { return true; } else { - utils.logWarn('Invalid mediaType banner.'); + logWarn('Invalid mediaType banner.'); } return false; } @@ -35,7 +35,7 @@ function buildRequests(validBidRequests, bidderRequest) { for (let i = 0; i < validBidRequests.length; i++) { const bidRequest = validBidRequests[i]; - const placementId = utils.getBidIdParameter('placementId', bidRequest.params); + const placementId = getBidIdParameter('placementId', bidRequest.params); const bidDomain = bidRequest.params.domain || BIDDER_DOMAIN; const bidUrl = `https://${bidDomain}/bid/v1/prebid/${placementId}`; const uuid = getUuid(); @@ -44,12 +44,12 @@ function buildRequests(validBidRequests, bidderRequest) { let height = 0; if (hasVideoMediaType(bidRequest) && isVideoValid(bidRequest)) { - const playerSize = getValidSizes(utils.deepAccess(bidRequest, 'mediaTypes.video.playerSize')); + const playerSize = getValidSizes(deepAccess(bidRequest, 'mediaTypes.video.playerSize')); width = playerSize[0][0]; height = playerSize[0][1]; mediaType = VIDEO; } else if (hasBannerMediaType(bidRequest) && isBannerValid(bidRequest)) { - const sizes = getValidSizes(utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes')); + const sizes = getValidSizes(deepAccess(bidRequest, 'mediaTypes.banner.sizes')); width = sizes[0][0]; height = sizes[0][1]; mediaType = BANNER; @@ -136,7 +136,7 @@ function getUserSyncs(syncOptions, serverResponses) { } let syncUrl = `https://${BIDDER_DOMAIN}/tr/v1/prebid/sync.html`; if (serverResponses.length > 0) { - syncUrl = utils.deepAccess(serverResponses, '0.body.syncUrl') || syncUrl; + syncUrl = deepAccess(serverResponses, '0.body.syncUrl') || syncUrl; } return [{ type: 'iframe', @@ -145,34 +145,34 @@ function getUserSyncs(syncOptions, serverResponses) { } function onBidWon(bid) { - let query = utils.parseQueryStringParameters({ - placement_id: utils.deepAccess(bid, 'params.0.placementId'), - creative_id: utils.deepAccess(bid, 'creativeId'), - price: utils.deepAccess(bid, 'cpm'), - auction_id: utils.deepAccess(bid, 'auctionId'), - bid_id: utils.deepAccess(bid, 'requestId'), - ad_id: utils.deepAccess(bid, 'adId'), - ad_unit_code: utils.deepAccess(bid, 'adUnitCode'), + let query = parseQueryStringParameters({ + placement_id: deepAccess(bid, 'params.0.placementId'), + creative_id: deepAccess(bid, 'creativeId'), + price: deepAccess(bid, 'cpm'), + auction_id: deepAccess(bid, 'auctionId'), + bid_id: deepAccess(bid, 'requestId'), + ad_id: deepAccess(bid, 'adId'), + ad_unit_code: deepAccess(bid, 'adUnitCode'), ref: window.location.href, }).replace(/\&$/, ''); - const bidDomain = utils.deepAccess(bid, 'params.0.domain') || BIDDER_DOMAIN; + const bidDomain = deepAccess(bid, 'params.0.domain') || BIDDER_DOMAIN; const burl = `https://${bidDomain}/tr/v1/prebid/win.gif?${query}`; - utils.triggerPixel(burl); + triggerPixel(burl); } function onTimeout(data) { - let query = utils.parseQueryStringParameters({ - placement_id: utils.deepAccess(data, '0.params.0.placementId'), - timeout: utils.deepAccess(data, '0.timeout'), - auction_id: utils.deepAccess(data, '0.auctionId'), - bid_id: utils.deepAccess(data, '0.bidId'), - ad_unit_code: utils.deepAccess(data, '0.adUnitCode'), + let query = parseQueryStringParameters({ + placement_id: deepAccess(data, '0.params.0.placementId'), + timeout: deepAccess(data, '0.timeout'), + auction_id: deepAccess(data, '0.auctionId'), + bid_id: deepAccess(data, '0.bidId'), + ad_unit_code: deepAccess(data, '0.adUnitCode'), version: ADAPTER_VERSION, ref: window.location.href, }).replace(/\&$/, ''); - const bidDomain = utils.deepAccess(data, '0.params.0.domain') || BIDDER_DOMAIN; + const bidDomain = deepAccess(data, '0.params.0.domain') || BIDDER_DOMAIN; const timeoutUrl = `https://${bidDomain}/tr/v1/prebid/timeout.gif?${query}`; - utils.triggerPixel(timeoutUrl); + triggerPixel(timeoutUrl); } function createPlayerTag(playerUrl) { @@ -199,7 +199,7 @@ function newRenderer(bidId, playerUrl) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('renderer.setRender Error', err); + logWarn('renderer.setRender Error', err); } return renderer; } @@ -220,7 +220,7 @@ function isBannerValid(bid) { if (!isMobile()) { return false; } - const sizes = getValidSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes')); + const sizes = getValidSizes(deepAccess(bid, 'mediaTypes.banner.sizes')); if (sizes.length > 0) { return true; } @@ -228,9 +228,9 @@ function isBannerValid(bid) { } function isVideoValid(bid) { - const playerSize = getValidSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize')); + const playerSize = getValidSizes(deepAccess(bid, 'mediaTypes.video.playerSize')); if (playerSize.length > 0) { - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const context = deepAccess(bid, 'mediaTypes.video.context'); if (context && context === 'outstream') { return true; } @@ -241,7 +241,7 @@ function isVideoValid(bid) { function getUuid() { const id = storage.getCookie(UUID_KEY) if (id) return id; - const newId = utils.generateUUID(); + const newId = generateUUID(); storage.setCookie(UUID_KEY, newId); return newId; } @@ -255,18 +255,18 @@ export function isMobile() { } function hasBannerMediaType(bid) { - return !!utils.deepAccess(bid, 'mediaTypes.banner'); + return !!deepAccess(bid, 'mediaTypes.banner'); } function hasVideoMediaType(bid) { - return !!utils.deepAccess(bid, 'mediaTypes.video'); + return !!deepAccess(bid, 'mediaTypes.video'); } function getValidSizes(sizes) { let result = []; - if (sizes && utils.isArray(sizes) && sizes.length > 0) { + if (sizes && isArray(sizes) && sizes.length > 0) { for (let i = 0; i < sizes.length; i++) { - if (utils.isArray(sizes[i]) && sizes[i].length == 2) { + if (isArray(sizes[i]) && sizes[i].length == 2) { const width = sizes[i][0]; const height = sizes[i][1]; if (width == 1 && height == 1) { diff --git a/modules/resetdigitalBidAdapter.js b/modules/resetdigitalBidAdapter.js index 7591c3391a0..255ee32629c 100644 --- a/modules/resetdigitalBidAdapter.js +++ b/modules/resetdigitalBidAdapter.js @@ -1,8 +1,7 @@ -import * as utils from '../src/utils.js'; +import { timestamp, deepAccess, getOrigin } from '../src/utils.js'; import { config } from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import {getOrigin} from '../src/utils.js'; const BIDDER_CODE = 'resetdigital'; export const spec = { @@ -20,7 +19,7 @@ export const spec = { ? config.getConfig('userSync').syncsPerBidder : 5 const payload = { - start_time: utils.timestamp(), + start_time: timestamp(), language: window.navigator.userLanguage || window.navigator.language, site: { domain: getOrigin(), @@ -51,7 +50,7 @@ export const spec = { imp_id: req.transactionId, sizes: req.sizes, force_bid: req.params.forceBid, - media_types: utils.deepAccess(req, 'mediaTypes') + media_types: deepAccess(req, 'mediaTypes') }); } diff --git a/modules/revcontentBidAdapter.js b/modules/revcontentBidAdapter.js index 777060a5eb6..0888e5ad1b4 100644 --- a/modules/revcontentBidAdapter.js +++ b/modules/revcontentBidAdapter.js @@ -3,7 +3,7 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { triggerPixel, isFn, deepAccess, getAdUnitSizes, parseGPTSingleSizeArrayToRtbSize, _map } from '../src/utils.js'; const BIDDER_CODE = 'revcontent'; const NATIVE_PARAMS = { @@ -160,7 +160,7 @@ export const spec = { }, onBidWon: function (bid) { if (bid.nurl) { - utils.triggerPixel(bid.nurl); + triggerPixel(bid.nurl); } return true; } @@ -215,14 +215,14 @@ function extractHostname(url) { function buildImp(bid, id) { let bidfloor; - if (utils.isFn(bid.getFloor)) { + if (isFn(bid.getFloor)) { bidfloor = bid.getFloor({ currency: 'USD', mediaType: '*', size: '*' }).floor; } else { - bidfloor = utils.deepAccess(bid, `params.bidfloor`) || 0.1; + bidfloor = deepAccess(bid, `params.bidfloor`) || 0.1; } let imp = { @@ -236,17 +236,17 @@ function buildImp(bid, id) { secure: '1' }; - let bannerReq = utils.deepAccess(bid, `mediaTypes.banner`); - let nativeReq = utils.deepAccess(bid, `mediaTypes.native`); + let bannerReq = deepAccess(bid, `mediaTypes.banner`); + let nativeReq = deepAccess(bid, `mediaTypes.native`); if (bannerReq) { - let sizes = utils.getAdUnitSizes(bid); + let sizes = getAdUnitSizes(bid); imp.banner = { w: sizes[0][0], h: sizes[0][1], - format: sizes.map(wh => utils.parseGPTSingleSizeArrayToRtbSize(wh)), + format: sizes.map(wh => parseGPTSingleSizeArrayToRtbSize(wh)), } } else if (nativeReq) { - const assets = utils._map(bid.nativeParams, (bidParams, key) => { + const assets = _map(bid.nativeParams, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1 From ac9ef03638ee6b584e7bba2432ce57543ab18059 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 09:25:29 -0700 Subject: [PATCH 13/14] import utils functions as needed and not the whole module --- modules/rhythmoneBidAdapter.js | 33 ++++++++++---------- modules/richaudienceBidAdapter.js | 18 +++++------ modules/riseBidAdapter.js | 52 +++++++++++++++---------------- modules/roxotAnalyticsAdapter.js | 28 ++++++++--------- modules/rtbhouseBidAdapter.js | 14 ++++----- 5 files changed, 73 insertions(+), 72 deletions(-) diff --git a/modules/rhythmoneBidAdapter.js b/modules/rhythmoneBidAdapter.js index 36b2c369213..d0e399ab7e3 100644 --- a/modules/rhythmoneBidAdapter.js +++ b/modules/rhythmoneBidAdapter.js @@ -1,6 +1,7 @@ + 'use strict'; -import * as utils from '../src/utils.js'; +import { deepAccess, getDNT, parseSizesInput, isArray } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -41,13 +42,13 @@ function RhythmOneBidAdapter() { impObj.bidfloor = 0; impObj.secure = isSecure; - if (utils.deepAccess(BRs[i], 'mediaTypes.banner') || utils.deepAccess(BRs[i], 'mediaType') === 'banner') { + if (deepAccess(BRs[i], 'mediaTypes.banner') || deepAccess(BRs[i], 'mediaType') === 'banner') { let banner = frameBanner(BRs[i]); if (banner) { impObj.banner = banner; } } - if (utils.deepAccess(BRs[i], 'mediaTypes.video') || utils.deepAccess(BRs[i], 'mediaType') === 'video') { + if (deepAccess(BRs[i], 'mediaTypes.video') || deepAccess(BRs[i], 'mediaType') === 'video') { impObj.video = frameVideo(BRs[i]); } if (!(impObj.banner || impObj.video)) { @@ -85,7 +86,7 @@ function RhythmOneBidAdapter() { return { ua: navigator.userAgent, ip: '', // Empty Ip string is required, server gets the ip from HTTP header - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, } } @@ -105,7 +106,7 @@ function RhythmOneBidAdapter() { if (adUnit.mediaTypes && adUnit.mediaTypes.banner) { sizeList = adUnit.mediaTypes.banner.sizes; } - var sizeStringList = utils.parseSizesInput(sizeList); + var sizeStringList = parseSizesInput(sizeList); var format = []; sizeStringList.forEach(function(size) { if (size) { @@ -129,9 +130,9 @@ function RhythmOneBidAdapter() { function frameVideo(bid) { var size = []; - if (utils.deepAccess(bid, 'mediaTypes.video.playerSize')) { + if (deepAccess(bid, 'mediaTypes.video.playerSize')) { var dimensionSet = bid.mediaTypes.video.playerSize; - if (utils.isArray(bid.mediaTypes.video.playerSize[0])) { + if (isArray(bid.mediaTypes.video.playerSize[0])) { dimensionSet = bid.mediaTypes.video.playerSize[0]; } var validSize = getValidSizeSet(dimensionSet) @@ -140,15 +141,15 @@ function RhythmOneBidAdapter() { } } return { - mimes: utils.deepAccess(bid, 'mediaTypes.video.mimes') || SUPPORTED_VIDEO_MIMES, - protocols: utils.deepAccess(bid, 'mediaTypes.video.protocols') || SUPPORTED_VIDEO_PROTOCOLS, + mimes: deepAccess(bid, 'mediaTypes.video.mimes') || SUPPORTED_VIDEO_MIMES, + protocols: deepAccess(bid, 'mediaTypes.video.protocols') || SUPPORTED_VIDEO_PROTOCOLS, w: size[0], h: size[1], - startdelay: utils.deepAccess(bid, 'mediaTypes.video.startdelay') || 0, - skip: utils.deepAccess(bid, 'mediaTypes.video.skip') || 0, - playbackmethod: utils.deepAccess(bid, 'mediaTypes.video.playbackmethod') || SUPPORTED_VIDEO_PLAYBACK_METHODS, - delivery: utils.deepAccess(bid, 'mediaTypes.video.delivery') || SUPPORTED_VIDEO_DELIVERY, - api: utils.deepAccess(bid, 'mediaTypes.video.api') || SUPPORTED_VIDEO_API, + startdelay: deepAccess(bid, 'mediaTypes.video.startdelay') || 0, + skip: deepAccess(bid, 'mediaTypes.video.skip') || 0, + playbackmethod: deepAccess(bid, 'mediaTypes.video.playbackmethod') || SUPPORTED_VIDEO_PLAYBACK_METHODS, + delivery: deepAccess(bid, 'mediaTypes.video.delivery') || SUPPORTED_VIDEO_DELIVERY, + api: deepAccess(bid, 'mediaTypes.video.api') || SUPPORTED_VIDEO_API, } } @@ -170,14 +171,14 @@ function RhythmOneBidAdapter() { device: frameDevice(), user: { ext: { - consent: utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? bidderRequest.gdprConsent.consentString : '' + consent: deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? bidderRequest.gdprConsent.consentString : '' } }, at: 1, tmax: 1000, regs: { ext: { - gdpr: utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? Boolean(bidderRequest.gdprConsent.gdprApplies & 1) : false + gdpr: deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? Boolean(bidderRequest.gdprConsent.gdprApplies & 1) : false } } }; diff --git a/modules/richaudienceBidAdapter.js b/modules/richaudienceBidAdapter.js index 4b556e83236..eace460eb22 100755 --- a/modules/richaudienceBidAdapter.js +++ b/modules/richaudienceBidAdapter.js @@ -1,7 +1,7 @@ +import { isEmpty, deepAccess, isStr } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {config} from '../src/config.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; const BIDDER_CODE = 'richaudience'; @@ -52,7 +52,7 @@ export const spec = { videoData: raiGetVideoInfo(bid), scr_rsl: raiGetResolution(), cpuc: (typeof window.navigator != 'undefined' ? window.navigator.hardwareConcurrency : null), - kws: (!utils.isEmpty(bid.params.keywords) ? bid.params.keywords : null) + kws: (!isEmpty(bid.params.keywords) ? bid.params.keywords : null) }; REFERER = (typeof bidderRequest.refererInfo.referer != 'undefined' ? encodeURIComponent(bidderRequest.refererInfo.referer) : null) @@ -220,19 +220,19 @@ function raiSetEids(bid) { let eids = []; if (bid && bid.userId) { - raiSetUserId(bid, eids, 'id5-sync.com', utils.deepAccess(bid, `userId.id5id.uid`)); - raiSetUserId(bid, eids, 'pubcommon', utils.deepAccess(bid, `userId.pubcid`)); - raiSetUserId(bid, eids, 'criteo.com', utils.deepAccess(bid, `userId.criteoId`)); - raiSetUserId(bid, eids, 'liveramp.com', utils.deepAccess(bid, `userId.idl_env`)); - raiSetUserId(bid, eids, 'liveintent.com', utils.deepAccess(bid, `userId.lipb.lipbid`)); - raiSetUserId(bid, eids, 'adserver.org', utils.deepAccess(bid, `userId.tdid`)); + raiSetUserId(bid, eids, 'id5-sync.com', deepAccess(bid, `userId.id5id.uid`)); + raiSetUserId(bid, eids, 'pubcommon', deepAccess(bid, `userId.pubcid`)); + raiSetUserId(bid, eids, 'criteo.com', deepAccess(bid, `userId.criteoId`)); + raiSetUserId(bid, eids, 'liveramp.com', deepAccess(bid, `userId.idl_env`)); + raiSetUserId(bid, eids, 'liveintent.com', deepAccess(bid, `userId.lipb.lipbid`)); + raiSetUserId(bid, eids, 'adserver.org', deepAccess(bid, `userId.tdid`)); } return eids; } function raiSetUserId(bid, eids, source, value) { - if (utils.isStr(value)) { + if (isStr(value)) { eids.push({ userId: value, source: source diff --git a/modules/riseBidAdapter.js b/modules/riseBidAdapter.js index 492653afb95..7f84dbd3344 100644 --- a/modules/riseBidAdapter.js +++ b/modules/riseBidAdapter.js @@ -1,5 +1,5 @@ +import { logWarn, isArray, isFn, deepAccess, isEmpty, contains, timestamp, getBidIdParameter } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import {VIDEO} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -25,12 +25,12 @@ export const spec = { supportedMediaTypes: SUPPORTED_AD_TYPES, isBidRequestValid: function(bidRequest) { if (!bidRequest.params) { - utils.logWarn('no params have been set to Rise adapter'); + logWarn('no params have been set to Rise adapter'); return false; } if (!bidRequest.params.org) { - utils.logWarn('org is a mandatory param for Rise adapter'); + logWarn('org is a mandatory param for Rise adapter'); return false; } @@ -82,7 +82,7 @@ export const spec = { url: response.body.userSyncURL }); } - if (syncOptions.pixelEnabled && utils.isArray(response.body.userSyncPixels)) { + if (syncOptions.pixelEnabled && isArray(response.body.userSyncPixels)) { const pixels = response.body.userSyncPixels.map(pixel => { return { type: 'image', @@ -104,7 +104,7 @@ registerBidder(spec); * @returns {Number} */ function getFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return 0; } let floorResult = bid.getFloor({ @@ -137,7 +137,7 @@ function buildVideoRequest(bid, bidderRequest) { * @returns {Array} */ function getSizes(bid) { - if (utils.deepAccess(bid, 'mediaTypes.video.sizes')) { + if (deepAccess(bid, 'mediaTypes.video.sizes')) { return bid.mediaTypes.video.sizes[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { return bid.sizes[0]; @@ -151,7 +151,7 @@ function getSizes(bid) { * @returns {string} */ function getSupplyChain(schainObject) { - if (utils.isEmpty(schainObject)) { + if (isEmpty(schainObject)) { return ''; } let scStr = `${schainObject.ver},${schainObject.complete}`; @@ -173,7 +173,7 @@ function getSupplyChain(schainObject) { * @returns {string} */ function getEncodedValIfNotEmpty(val) { - return !utils.isEmpty(val) ? encodeURIComponent(val) : ''; + return !isEmpty(val) ? encodeURIComponent(val) : ''; } /** @@ -203,8 +203,8 @@ function isSyncMethodAllowed(syncRule, bidderCode) { return false; } const isInclude = syncRule.filter === 'include'; - const bidders = utils.isArray(syncRule.bidders) ? syncRule.bidders : [bidderCode]; - return isInclude && utils.contains(bidders, bidderCode); + const bidders = isArray(syncRule.bidders) ? syncRule.bidders : [bidderCode]; + return isInclude && contains(bidders, bidderCode); } /** @@ -263,25 +263,25 @@ function generateParameters(bid, bidderRequest) { wrapper_vendor: '$$PREBID_GLOBAL$$', wrapper_version: '$prebid.version$', adapter_version: ADAPTER_VERSION, - auction_start: utils.timestamp(), - ad_unit_code: utils.getBidIdParameter('adUnitCode', bid), + auction_start: timestamp(), + ad_unit_code: getBidIdParameter('adUnitCode', bid), tmax: timeout, width: width, height: height, publisher_id: params.org, floor_price: Math.max(getFloor(bid), params.floorPrice), ua: navigator.userAgent, - bid_id: utils.getBidIdParameter('bidId', bid), - bidder_request_id: utils.getBidIdParameter('bidderRequestId', bid), - transaction_id: utils.getBidIdParameter('transactionId', bid), - session_id: utils.getBidIdParameter('auctionId', bid), + bid_id: getBidIdParameter('bidId', bid), + bidder_request_id: getBidIdParameter('bidderRequestId', bid), + transaction_id: getBidIdParameter('transactionId', bid), + session_id: getBidIdParameter('auctionId', bid), publisher_name: domain, site_domain: domain, dnt: (navigator.doNotTrack == 'yes' || navigator.doNotTrack == '1' || navigator.msDoNotTrack == '1') ? 1 : 0, device_type: getDeviceType(navigator.userAgent) }; - const userIdsParam = utils.getBidIdParameter('userId', bid); + const userIdsParam = getBidIdParameter('userId', bid); if (userIdsParam) { requestParams.userIds = JSON.stringify(userIdsParam); } @@ -294,31 +294,31 @@ function generateParameters(bid, bidderRequest) { requestParams.user_metadata = JSON.stringify(ortb2Metadata.user); } - const playbackMethod = utils.deepAccess(bid, 'mediaTypes.video.playbackmethod'); + const playbackMethod = deepAccess(bid, 'mediaTypes.video.playbackmethod'); if (playbackMethod) { requestParams.playback_method = playbackMethod; } - const placement = utils.deepAccess(bid, 'mediaTypes.video.placement'); + const placement = deepAccess(bid, 'mediaTypes.video.placement'); if (placement) { requestParams.placement = placement; } - const pos = utils.deepAccess(bid, 'mediaTypes.video.pos'); + const pos = deepAccess(bid, 'mediaTypes.video.pos'); if (pos) { requestParams.pos = pos; } - const minduration = utils.deepAccess(bid, 'mediaTypes.video.minduration'); + const minduration = deepAccess(bid, 'mediaTypes.video.minduration'); if (minduration) { requestParams.min_duration = minduration; } - const maxduration = utils.deepAccess(bid, 'mediaTypes.video.maxduration'); + const maxduration = deepAccess(bid, 'mediaTypes.video.maxduration'); if (maxduration) { requestParams.max_duration = maxduration; } - const skip = utils.deepAccess(bid, 'mediaTypes.video.skip'); + const skip = deepAccess(bid, 'mediaTypes.video.skip'); if (skip) { requestParams.skip = skip; } - const linearity = utils.deepAccess(bid, 'mediaTypes.video.linearity'); + const linearity = deepAccess(bid, 'mediaTypes.video.linearity'); if (linearity) { requestParams.linearity = linearity; } @@ -352,8 +352,8 @@ function generateParameters(bid, bidderRequest) { } if (bidderRequest && bidderRequest.refererInfo) { - requestParams.referrer = utils.deepAccess(bidderRequest, 'refererInfo.referer'); - requestParams.page_url = config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); + requestParams.referrer = deepAccess(bidderRequest, 'refererInfo.referer'); + requestParams.page_url = config.getConfig('pageUrl') || deepAccess(window, 'location.href'); } return requestParams; diff --git a/modules/roxotAnalyticsAdapter.js b/modules/roxotAnalyticsAdapter.js index b6857d69f45..c9245d4ae08 100644 --- a/modules/roxotAnalyticsAdapter.js +++ b/modules/roxotAnalyticsAdapter.js @@ -1,3 +1,4 @@ +import { deepClone, getParameterByName, logInfo, logError } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; @@ -7,7 +8,6 @@ import { getStorageManager } from '../src/storageManager.js'; const storage = getStorageManager(); -const utils = require('../src/utils.js'); let ajax = ajaxBuilder(0); const DEFAULT_EVENT_URL = 'pa.rxthdr.com/v3'; @@ -153,7 +153,7 @@ function buildBidderRequest(auction, bidRequest) { function buildBidAfterTimeout(adUnitAuction, args) { return { - 'auction': utils.deepClone(adUnitAuction), + 'auction': deepClone(adUnitAuction), 'adUnit': extractAdUnitCode(args), 'bidder': extractBidder(args), 'cpm': args.cpm, @@ -170,7 +170,7 @@ function buildBidAfterTimeout(adUnitAuction, args) { function buildImpression(adUnitAuction, args) { return { 'isNew': checkIsNewFlag() ? 1 : 0, - 'auction': utils.deepClone(adUnitAuction), + 'auction': deepClone(adUnitAuction), 'adUnit': extractAdUnitCode(args), 'bidder': extractBidder(args), 'cpm': args.cpm, @@ -342,7 +342,7 @@ roxotAdapter.originEnableAnalytics = roxotAdapter.enableAnalytics; roxotAdapter.enableAnalytics = function (config) { if (this.initConfig(config)) { - logInfo('Analytics adapter enabled', initOptions); + _logInfo('Analytics adapter enabled', initOptions); roxotAdapter.originEnableAnalytics(config); } }; @@ -351,7 +351,7 @@ roxotAdapter.buildUtmTagData = function () { let utmTagData = {}; let utmTagsDetected = false; utmTags.forEach(function (utmTagKey) { - let utmTagValue = utils.getParameterByName(utmTagKey); + let utmTagValue = getParameterByName(utmTagKey); if (utmTagValue !== '') { utmTagsDetected = true; } @@ -374,11 +374,11 @@ roxotAdapter.buildUtmTagData = function () { roxotAdapter.initConfig = function (config) { let isCorrectConfig = true; initOptions = {}; - initOptions.options = utils.deepClone(config.options); + initOptions.options = deepClone(config.options); initOptions.publisherId = initOptions.options.publisherId || (initOptions.options.publisherIds[0]) || null; if (!initOptions.publisherId) { - logError('"options.publisherId" is empty'); + _logError('"options.publisherId" is empty'); isCorrectConfig = false; } @@ -407,7 +407,7 @@ function registerEvent(eventType, eventName, data) { sendEventCache.push(eventData); - logInfo('Register event', eventData); + _logInfo('Register event', eventData); (typeof initOptions.serverConfig === 'undefined') ? checkEventAfterTimeout() : checkSendEvent(); } @@ -427,7 +427,7 @@ function checkSendEvent() { let event = sendEventCache.shift(); let isNeedSend = initOptions.serverConfig[event.eventType] || 0; if (Number(isNeedSend) === 0) { - logInfo('Skip event ' + event.eventName, event); + _logInfo('Skip event ' + event.eventName, event); continue; } sendEvent(event.eventType, event.eventName, event.data); @@ -454,7 +454,7 @@ function sendEvent(eventType, eventName, data) { ajax( url, function () { - logInfo(eventName + ' sent', eventData); + _logInfo(eventName + ' sent', eventData); }, JSON.stringify(eventData), { @@ -490,12 +490,12 @@ function loadServerConfig() { ); } -function logInfo(message, meta) { - utils.logInfo(buildLogMessage(message), meta); +function _logInfo(message, meta) { + logInfo(buildLogMessage(message), meta); } -function logError(message) { - utils.logError(buildLogMessage(message)); +function _logError(message) { + logError(buildLogMessage(message)); } function buildLogMessage(message) { diff --git a/modules/rtbhouseBidAdapter.js b/modules/rtbhouseBidAdapter.js index 036bdfaebeb..2c562e5841a 100644 --- a/modules/rtbhouseBidAdapter.js +++ b/modules/rtbhouseBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isArray, deepAccess, getOrigin, logError } from '../src/utils.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import includes from 'core-js-pure/features/array/includes.js'; @@ -82,7 +82,7 @@ export const spec = { }, interpretResponse: function (serverResponse, originalRequest) { const responseBody = serverResponse.body; - if (!utils.isArray(responseBody)) { + if (!isArray(responseBody)) { return []; } @@ -145,7 +145,7 @@ function mapImpression(slot) { */ function mapBanner(slot) { if (slot.mediaType === 'banner' || - utils.deepAccess(slot, 'mediaTypes.banner') || + deepAccess(slot, 'mediaTypes.banner') || (!slot.mediaType && !slot.mediaTypes)) { var sizes = slot.sizes || slot.mediaTypes.banner.sizes; return { @@ -173,7 +173,7 @@ function mapSite(slot, bidderRequest) { id: pubId.toString(), }, page: bidderRequest.refererInfo.referer, - name: utils.getOrigin() + name: getOrigin() } } @@ -198,7 +198,7 @@ function mapSchain(schain) { return null; } if (!validateSchain(schain)) { - utils.logError('RTB House: required schain params missing'); + logError('RTB House: required schain params missing'); return null; } return schain; @@ -223,7 +223,7 @@ function validateSchain(schain) { * @returns {object} Request by OpenRTB Native Ads 1.1 §4 */ function mapNative(slot) { - if (slot.mediaType === 'native' || utils.deepAccess(slot, 'mediaTypes.native')) { + if (slot.mediaType === 'native' || deepAccess(slot, 'mediaTypes.native')) { return { request: { assets: mapNativeAssets(slot) @@ -238,7 +238,7 @@ function mapNative(slot) { * @returns {array} Request Assets by OpenRTB Native Ads 1.1 §4.2 */ function mapNativeAssets(slot) { - const params = slot.nativeParams || utils.deepAccess(slot, 'mediaTypes.native'); + const params = slot.nativeParams || deepAccess(slot, 'mediaTypes.native'); const assets = []; if (params.title) { assets.push({ From 98504358546ca0e706c789db93e09ea6776c16fa Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 10:40:26 -0700 Subject: [PATCH 14/14] import utils functions as needed and not the whole module --- modules/rtbsapeBidAdapter.js | 7 +- modules/rubiconAnalyticsAdapter.js | 138 +++++++++++++-------------- modules/rubiconBidAdapter.js | 134 +++++++++++++------------- modules/scaleableAnalyticsAdapter.js | 4 +- modules/seedingAllianceBidAdapter.js | 12 +-- 5 files changed, 147 insertions(+), 148 deletions(-) diff --git a/modules/rtbsapeBidAdapter.js b/modules/rtbsapeBidAdapter.js index f5c648d5234..d58b3a1f240 100644 --- a/modules/rtbsapeBidAdapter.js +++ b/modules/rtbsapeBidAdapter.js @@ -1,9 +1,8 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, triggerPixel } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {OUTSTREAM} from '../src/video.js'; import {Renderer} from '../src/Renderer.js'; -import {triggerPixel} from '../src/utils.js'; const BIDDER_CODE = 'rtbsape'; const ENDPOINT = 'https://ssp-rtb.sape.ru/prebid'; @@ -68,7 +67,7 @@ export const spec = { .filter(bid => typeof (bid.meta || {}).advertiserDomains !== 'undefined') .map(bid => { let requestBid = bids[bid.requestId]; - let context = utils.deepAccess(requestBid, 'mediaTypes.video.context'); + let context = deepAccess(requestBid, 'mediaTypes.video.context'); if (context === OUTSTREAM && (bid.vastUrl || bid.vastXml)) { let renderer = Renderer.install({ @@ -77,7 +76,7 @@ export const spec = { loaded: false }); - let muted = utils.deepAccess(requestBid, 'params.video.playerMuted'); + let muted = deepAccess(requestBid, 'params.video.playerMuted'); if (typeof muted === 'undefined') { muted = true; } diff --git a/modules/rubiconAnalyticsAdapter.js b/modules/rubiconAnalyticsAdapter.js index 3222c673a1b..5b17048cbd3 100644 --- a/modules/rubiconAnalyticsAdapter.js +++ b/modules/rubiconAnalyticsAdapter.js @@ -1,9 +1,9 @@ +import { generateUUID, mergeDeep, deepAccess, parseUrl, logError, pick, isEmpty, logWarn, debugTurnedOn, parseQS, getWindowLocation, isAdUnitCodeMatchingSlot, isNumber, isGptPubadsDefined, _each, deepSetValue } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; import { ajax } from '../src/ajax.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { getGlobal } from '../src/prebidGlobal.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -60,23 +60,23 @@ const cache = { const BID_REJECTED_IPF = 'rejected-ipf'; export let rubiConf = { - pvid: utils.generateUUID().slice(0, 8), + pvid: generateUUID().slice(0, 8), analyticsEventDelay: 0 }; // we are saving these as global to this module so that if a pub accidentally overwrites the entire // rubicon object, then we do not lose other data config.getConfig('rubicon', config => { - utils.mergeDeep(rubiConf, config.rubicon); - if (utils.deepAccess(config, 'rubicon.updatePageView') === true) { - rubiConf.pvid = utils.generateUUID().slice(0, 8) + mergeDeep(rubiConf, config.rubicon); + if (deepAccess(config, 'rubicon.updatePageView') === true) { + rubiConf.pvid = generateUUID().slice(0, 8) } }); export function getHostNameFromReferer(referer) { try { - rubiconAdapter.referrerHostname = utils.parseUrl(referer, { noDecodeWholeURL: true }).hostname; + rubiconAdapter.referrerHostname = parseUrl(referer, { noDecodeWholeURL: true }).hostname; } catch (e) { - utils.logError('Rubicon Analytics: Unable to parse hostname from supplied url: ', referer, e); + logError('Rubicon Analytics: Unable to parse hostname from supplied url: ', referer, e); rubiconAdapter.referrerHostname = ''; } return rubiconAdapter.referrerHostname @@ -117,10 +117,10 @@ function formatSource(src) { function sendMessage(auctionId, bidWonId, trigger) { function formatBid(bid) { - return utils.pick(bid, [ + return pick(bid, [ 'bidder', 'bidderDetail', - 'bidId', bidId => utils.deepAccess(bid, 'bidResponse.pbsBidId') || utils.deepAccess(bid, 'bidResponse.seatBidId') || bidId, + 'bidId', bidId => deepAccess(bid, 'bidResponse.pbsBidId') || deepAccess(bid, 'bidResponse.seatBidId') || bidId, 'status', 'error', 'source', (source, bid) => { @@ -133,7 +133,7 @@ function sendMessage(auctionId, bidWonId, trigger) { 'clientLatencyMillis', 'serverLatencyMillis', 'params', - 'bidResponse', bidResponse => bidResponse ? utils.pick(bidResponse, [ + 'bidResponse', bidResponse => bidResponse ? pick(bidResponse, [ 'bidPriceUSD', 'dealId', 'dimensions', @@ -146,13 +146,13 @@ function sendMessage(auctionId, bidWonId, trigger) { ]); } function formatBidWon(bid) { - return Object.assign(formatBid(bid), utils.pick(bid.adUnit, [ + return Object.assign(formatBid(bid), pick(bid.adUnit, [ 'adUnitCode', 'transactionId', 'videoAdFormat', () => bid.videoAdFormat, 'mediaTypes' ]), { - adserverTargeting: !utils.isEmpty(cache.targeting[bid.adUnit.adUnitCode]) ? stringProperties(cache.targeting[bid.adUnit.adUnitCode]) : undefined, + adserverTargeting: !isEmpty(cache.targeting[bid.adUnit.adUnitCode]) ? stringProperties(cache.targeting[bid.adUnit.adUnitCode]) : undefined, bidwonStatus: 'success', // hard-coded for now accountId, siteId: bid.siteId, @@ -187,13 +187,13 @@ function sendMessage(auctionId, bidWonId, trigger) { let bid = auctionCache.bids[bidId]; let adUnit = adUnits[bid.adUnit.adUnitCode]; if (!adUnit) { - adUnit = adUnits[bid.adUnit.adUnitCode] = utils.pick(bid.adUnit, [ + adUnit = adUnits[bid.adUnit.adUnitCode] = pick(bid.adUnit, [ 'adUnitCode', 'transactionId', 'mediaTypes', 'dimensions', - 'adserverTargeting', () => !utils.isEmpty(cache.targeting[bid.adUnit.adUnitCode]) ? stringProperties(cache.targeting[bid.adUnit.adUnitCode]) : undefined, - 'gam', gam => !utils.isEmpty(gam) ? gam : undefined, + 'adserverTargeting', () => !isEmpty(cache.targeting[bid.adUnit.adUnitCode]) ? stringProperties(cache.targeting[bid.adUnit.adUnitCode]) : undefined, + 'gam', gam => !isEmpty(gam) ? gam : undefined, 'pbAdSlot', 'pattern' ]); @@ -203,10 +203,10 @@ function sendMessage(auctionId, bidWonId, trigger) { // Add site and zone id if not there and if we found a rubicon bidder if ((!adUnit.siteId || !adUnit.zoneId) && rubiconAliases.indexOf(bid.bidder) !== -1) { - if (utils.deepAccess(bid, 'params.accountId') == accountId) { + if (deepAccess(bid, 'params.accountId') == accountId) { adUnit.accountId = parseInt(accountId); - adUnit.siteId = parseInt(utils.deepAccess(bid, 'params.siteId')); - adUnit.zoneId = parseInt(utils.deepAccess(bid, 'params.zoneId')); + adUnit.siteId = parseInt(deepAccess(bid, 'params.siteId')); + adUnit.zoneId = parseInt(deepAccess(bid, 'params.zoneId')); } } @@ -229,7 +229,7 @@ function sendMessage(auctionId, bidWonId, trigger) { // This allows the bidWon events to have these params even in the case of a delayed render Object.keys(auctionCache.bids).forEach(function (bidId) { let adCode = auctionCache.bids[bidId].adUnit.adUnitCode; - Object.assign(auctionCache.bids[bidId], utils.pick(adUnitMap[adCode], ['accountId', 'siteId', 'zoneId'])); + Object.assign(auctionCache.bids[bidId], pick(adUnitMap[adCode], ['accountId', 'siteId', 'zoneId'])); }); let auction = { @@ -243,20 +243,20 @@ function sendMessage(auctionId, bidWonId, trigger) { // pick our of top level floor data we want to send! if (auctionCache.floorData) { if (auctionCache.floorData.location === 'noData') { - auction.floors = utils.pick(auctionCache.floorData, [ + auction.floors = pick(auctionCache.floorData, [ 'location', 'fetchStatus', 'floorProvider as provider' ]); } else { - auction.floors = utils.pick(auctionCache.floorData, [ + auction.floors = pick(auctionCache.floorData, [ 'location', 'modelVersion as modelName', 'modelWeight', 'modelTimestamp', 'skipped', - 'enforcement', () => utils.deepAccess(auctionCache.floorData, 'enforcements.enforceJS'), - 'dealsEnforced', () => utils.deepAccess(auctionCache.floorData, 'enforcements.floorDeals'), + 'enforcement', () => deepAccess(auctionCache.floorData, 'enforcements.enforceJS'), + 'dealsEnforced', () => deepAccess(auctionCache.floorData, 'enforcements.floorDeals'), 'skipRate', 'fetchStatus', 'floorMin', @@ -267,7 +267,7 @@ function sendMessage(auctionId, bidWonId, trigger) { // gather gdpr info if (auctionCache.gdprConsent) { - auction.gdpr = utils.pick(auctionCache.gdprConsent, [ + auction.gdpr = pick(auctionCache.gdprConsent, [ 'gdprApplies as applies', 'consentString', 'apiVersion as version' @@ -276,13 +276,13 @@ function sendMessage(auctionId, bidWonId, trigger) { // gather session info if (auctionCache.session) { - message.session = utils.pick(auctionCache.session, [ + message.session = pick(auctionCache.session, [ 'id', 'pvid', 'start', 'expires' ]); - if (!utils.isEmpty(auctionCache.session.fpkvs)) { + if (!isEmpty(auctionCache.session.fpkvs)) { message.fpkvs = Object.keys(auctionCache.session.fpkvs).map(key => { return { key, value: auctionCache.session.fpkvs[key] }; }); @@ -329,14 +329,14 @@ function sendMessage(auctionId, bidWonId, trigger) { } function adUnitIsOnlyInstream(adUnit) { - return adUnit.mediaTypes && Object.keys(adUnit.mediaTypes).length === 1 && utils.deepAccess(adUnit, 'mediaTypes.video.context') === 'instream'; + return adUnit.mediaTypes && Object.keys(adUnit.mediaTypes).length === 1 && deepAccess(adUnit, 'mediaTypes.video.context') === 'instream'; } function getBidPrice(bid) { // get the cpm from bidResponse let cpm; let currency; - if (bid.status === BID_REJECTED && utils.deepAccess(bid, 'floorData.cpmAfterAdjustments')) { + if (bid.status === BID_REJECTED && deepAccess(bid, 'floorData.cpmAfterAdjustments')) { // if bid was rejected and bid.floorData.cpmAfterAdjustments use it cpm = bid.floorData.cpmAfterAdjustments; currency = bid.floorData.floorCurrency; @@ -356,7 +356,7 @@ function getBidPrice(bid) { try { return Number(prebidGlobal.convertCurrency(cpm, currency, 'USD')); } catch (err) { - utils.logWarn('Rubicon Analytics Adapter: Could not determine the bidPriceUSD of the bid ', bid); + logWarn('Rubicon Analytics Adapter: Could not determine the bidPriceUSD of the bid ', bid); } } @@ -367,7 +367,7 @@ export function parseBidResponse(bid, previousBidResponse, auctionFloorData) { if (previousBidResponse && previousBidResponse.bidPriceUSD > responsePrice) { return previousBidResponse; } - return utils.pick(bid, [ + return pick(bid, [ 'bidPriceUSD', () => responsePrice, 'dealId', 'status', @@ -378,13 +378,13 @@ export function parseBidResponse(bid, previousBidResponse, auctionFloorData) { return (width && height) ? { width, height } : undefined; }, // Handling use case where pbs sends back 0 or '0' bidIds - 'pbsBidId', pbsBidId => pbsBidId == 0 ? utils.generateUUID() : pbsBidId, - 'seatBidId', seatBidId => seatBidId == 0 ? utils.generateUUID() : seatBidId, - 'floorValue', () => utils.deepAccess(bid, 'floorData.floorValue'), - 'floorRuleValue', () => utils.deepAccess(bid, 'floorData.floorRuleValue'), - 'floorRule', () => utils.debugTurnedOn() ? utils.deepAccess(bid, 'floorData.floorRule') : undefined, + 'pbsBidId', pbsBidId => pbsBidId == 0 ? generateUUID() : pbsBidId, + 'seatBidId', seatBidId => seatBidId == 0 ? generateUUID() : seatBidId, + 'floorValue', () => deepAccess(bid, 'floorData.floorValue'), + 'floorRuleValue', () => deepAccess(bid, 'floorData.floorRuleValue'), + 'floorRule', () => debugTurnedOn() ? deepAccess(bid, 'floorData.floorRule') : undefined, 'adomains', () => { - let adomains = utils.deepAccess(bid, 'meta.advertiserDomains'); + let adomains = deepAccess(bid, 'meta.advertiserDomains'); return Array.isArray(adomains) && adomains.length > 0 ? adomains.slice(0, 10) : undefined } ]); @@ -397,7 +397,7 @@ function getUtmParams() { let search; try { - search = utils.parseQS(utils.getWindowLocation().search); + search = parseQS(getWindowLocation().search); } catch (e) { search = {}; } @@ -445,7 +445,7 @@ function getRpaCookie() { try { return JSON.parse(window.atob(encodedCookie)); } catch (e) { - utils.logError(`Rubicon Analytics: Unable to decode ${COOKIE_NAME} value: `, e); + logError(`Rubicon Analytics: Unable to decode ${COOKIE_NAME} value: `, e); } } return {}; @@ -455,7 +455,7 @@ function setRpaCookie(decodedCookie) { try { storage.setDataInLocalStorage(COOKIE_NAME, window.btoa(JSON.stringify(decodedCookie))); } catch (e) { - utils.logError(`Rubicon Analytics: Unable to encode ${COOKIE_NAME} value: `, e); + logError(`Rubicon Analytics: Unable to encode ${COOKIE_NAME} value: `, e); } } @@ -468,7 +468,7 @@ function updateRpaCookie() { decodedRpaCookie.expires < currentTime ) { decodedRpaCookie = { - id: utils.generateUUID(), + id: generateUUID(), start: currentTime, expires: currentTime + END_EXPIRE_TIME, // six hours later, } @@ -485,7 +485,7 @@ function updateRpaCookie() { function subscribeToGamSlots() { window.googletag.pubads().addEventListener('slotRenderEnded', event => { - const isMatchingAdSlot = utils.isAdUnitCodeMatchingSlot(event.slot); + const isMatchingAdSlot = isAdUnitCodeMatchingSlot(event.slot); // loop through auctions and adUnits and mark the info Object.keys(cache.auctions).forEach(auctionId => { (Object.keys(cache.auctions[auctionId].bids) || []).forEach(bidId => { @@ -495,12 +495,12 @@ function subscribeToGamSlots() { // mark this adUnit as having been rendered by gam cache.auctions[auctionId].gamHasRendered[bid.adUnit.adUnitCode] = true; - bid.adUnit.gam = utils.pick(event, [ + bid.adUnit.gam = pick(event, [ // these come in as `null` from Gpt, which when stringified does not get removed // so set explicitly to undefined when not a number - 'advertiserId', advertiserId => utils.isNumber(advertiserId) ? advertiserId : undefined, - 'creativeId', creativeId => utils.isNumber(event.sourceAgnosticCreativeId) ? event.sourceAgnosticCreativeId : utils.isNumber(creativeId) ? creativeId : undefined, - 'lineItemId', lineItemId => utils.isNumber(event.sourceAgnosticLineItemId) ? event.sourceAgnosticLineItemId : utils.isNumber(lineItemId) ? lineItemId : undefined, + 'advertiserId', advertiserId => isNumber(advertiserId) ? advertiserId : undefined, + 'creativeId', creativeId => isNumber(event.sourceAgnosticCreativeId) ? event.sourceAgnosticCreativeId : isNumber(creativeId) ? creativeId : undefined, + 'lineItemId', lineItemId => isNumber(event.sourceAgnosticLineItemId) ? event.sourceAgnosticLineItemId : isNumber(lineItemId) ? lineItemId : undefined, 'adSlot', () => event.slot.getAdUnitPath(), 'isSlotEmpty', () => event.isEmpty || undefined ]); @@ -535,7 +535,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { if (config.options.endpoint) { this.getUrl = () => config.options.endpoint; } else { - utils.logError('required endpoint missing from rubicon analytics'); + logError('required endpoint missing from rubicon analytics'); error = true; } if (typeof config.options.sampling !== 'undefined') { @@ -543,7 +543,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { } if (typeof config.options.samplingFactor !== 'undefined') { if (typeof config.options.sampling !== 'undefined') { - utils.logWarn('Both options.samplingFactor and options.sampling enabled in rubicon analytics, defaulting to samplingFactor'); + logWarn('Both options.samplingFactor and options.sampling enabled in rubicon analytics, defaulting to samplingFactor'); } samplingFactor = parseFloat(config.options.samplingFactor); config.options.sampling = 1 / samplingFactor; @@ -553,10 +553,10 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { let validSamplingFactors = [1, 10, 20, 40, 100]; if (validSamplingFactors.indexOf(samplingFactor) === -1) { error = true; - utils.logError('invalid samplingFactor for rubicon analytics: ' + samplingFactor + ', must be one of ' + validSamplingFactors.join(', ')); + logError('invalid samplingFactor for rubicon analytics: ' + samplingFactor + ', must be one of ' + validSamplingFactors.join(', ')); } else if (!accountId) { error = true; - utils.logError('required accountId missing for rubicon analytics'); + logError('required accountId missing for rubicon analytics'); } if (!error) { @@ -575,26 +575,26 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { case AUCTION_INIT: // set the rubicon aliases setRubiconAliases(adapterManager.aliasRegistry); - let cacheEntry = utils.pick(args, [ + let cacheEntry = pick(args, [ 'timestamp', 'timeout' ]); cacheEntry.bids = {}; cacheEntry.bidsWon = {}; cacheEntry.gamHasRendered = {}; - cacheEntry.referrer = utils.deepAccess(args, 'bidderRequests.0.refererInfo.referer'); - const floorData = utils.deepAccess(args, 'bidderRequests.0.bids.0.floorData'); + cacheEntry.referrer = deepAccess(args, 'bidderRequests.0.refererInfo.referer'); + const floorData = deepAccess(args, 'bidderRequests.0.bids.0.floorData'); if (floorData) { cacheEntry.floorData = { ...floorData }; } - cacheEntry.gdprConsent = utils.deepAccess(args, 'bidderRequests.0.gdprConsent'); + cacheEntry.gdprConsent = deepAccess(args, 'bidderRequests.0.gdprConsent'); cacheEntry.session = storage.localStorageIsEnabled() && updateRpaCookie(); - cacheEntry.userIds = Object.keys(utils.deepAccess(args, 'bidderRequests.0.bids.0.userId', {})).map(id => { + cacheEntry.userIds = Object.keys(deepAccess(args, 'bidderRequests.0.bids.0.userId', {})).map(id => { return { provider: id, hasId: true } }); cache.auctions[args.auctionId] = cacheEntry; // register to listen to gpt events if not done yet - if (!cache.gpt.registered && utils.isGptPubadsDefined()) { + if (!cache.gpt.registered && isGptPubadsDefined()) { subscribeToGamSlots(); cache.gpt.registered = true; } else if (!cache.gpt.registered) { @@ -615,7 +615,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { cache.auctions[args.auctionId].gamHasRendered[bid.adUnitCode] = false; } - memo[bid.bidId] = utils.pick(bid, [ + memo[bid.bidId] = pick(bid, [ 'bidder', bidder => bidder.toLowerCase(), 'bidId', 'status', () => 'no-bid', // default a bid to no-bid until response is recieved or bid is timed out @@ -624,7 +624,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { switch (bid.bidder) { // specify bidder params we want here case 'rubicon': - return utils.pick(params, [ + return pick(params, [ 'accountId', 'siteId', 'zoneId' @@ -640,9 +640,9 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { 204: 'mid-roll', 205: 'post-roll', 207: 'vertical' - })[utils.deepAccess(bid, 'params.video.size_id')]; + })[deepAccess(bid, 'params.video.size_id')]; } else { - let startdelay = parseInt(utils.deepAccess(bid, 'params.video.startdelay'), 10); + let startdelay = parseInt(deepAccess(bid, 'params.video.startdelay'), 10); if (!isNaN(startdelay)) { if (startdelay > 0) { return 'mid-roll'; @@ -655,7 +655,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { } } }, - 'adUnit', () => utils.pick(bid, [ + 'adUnit', () => pick(bid, [ 'adUnitCode', 'transactionId', 'sizes as dimensions', sizes => sizes.map(sizeToDimensions), @@ -669,7 +669,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { if (typeof types === 'object') { if (!bid.sizes) { bid.dimensions = []; - utils._each(types, (type) => + _each(types, (type) => bid.dimensions = bid.dimensions.concat( type.sizes.map(sizeToDimensions) ) @@ -680,12 +680,12 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { return ['banner']; }, 'gam', () => { - if (utils.deepAccess(bid, 'ortb2Imp.ext.data.adserver.name') === 'gam') { + if (deepAccess(bid, 'ortb2Imp.ext.data.adserver.name') === 'gam') { return { adSlot: bid.ortb2Imp.ext.data.adserver.adslot } } }, - 'pbAdSlot', () => utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'), - 'pattern', () => utils.deepAccess(bid, 'ortb2Imp.ext.data.aupname') + 'pbAdSlot', () => deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'), + 'pattern', () => deepAccess(bid, 'ortb2Imp.ext.data.aupname') ]) ]); return memo; @@ -702,15 +702,15 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { let bid = auctionEntry.bids[args.requestId]; // If floor resolved gptSlot but we have not yet, then update the adUnit to have the adSlot name - if (!utils.deepAccess(bid, 'adUnit.gam.adSlot') && utils.deepAccess(args, 'floorData.matchedFields.gptSlot')) { - utils.deepSetValue(bid, 'adUnit.gam.adSlot', args.floorData.matchedFields.gptSlot); + if (!deepAccess(bid, 'adUnit.gam.adSlot') && deepAccess(args, 'floorData.matchedFields.gptSlot')) { + deepSetValue(bid, 'adUnit.gam.adSlot', args.floorData.matchedFields.gptSlot); } // if we have not set enforcements yet set it - if (!utils.deepAccess(auctionEntry, 'floorData.enforcements') && utils.deepAccess(args, 'floorData.enforcements')) { + if (!deepAccess(auctionEntry, 'floorData.enforcements') && deepAccess(args, 'floorData.enforcements')) { auctionEntry.floorData.enforcements = { ...args.floorData.enforcements }; } if (!bid) { - utils.logError('Rubicon Anlytics Adapter Error: Could not find associated bid request for bid response with requestId: ', args.requestId); + logError('Rubicon Anlytics Adapter Error: Could not find associated bid request for bid response with requestId: ', args.requestId); break; } bid.source = formatSource(bid.source || args.source); @@ -733,7 +733,7 @@ let rubiconAdapter = Object.assign({}, baseAdapter, { bid.bidResponse = parseBidResponse(args, bid.bidResponse); break; case BIDDER_DONE: - const serverError = utils.deepAccess(args, 'serverErrors.0'); + const serverError = deepAccess(args, 'serverErrors.0'); const serverResponseTimeMs = args.serverResponseTimeMs; args.bids.forEach(bid => { let cachedBid = cache.auctions[bid.auctionId].bids[bid.bidId || bid.requestId]; diff --git a/modules/rubiconBidAdapter.js b/modules/rubiconBidAdapter.js index d502d7efb25..8e3733af947 100644 --- a/modules/rubiconBidAdapter.js +++ b/modules/rubiconBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { mergeDeep, _each, logError, deepAccess, deepSetValue, isStr, isNumber, logWarn, convertTypes, isArray, parseSizesInput, logMessage } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {config} from '../src/config.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; @@ -15,7 +15,7 @@ let rubiConf = {}; // we are saving these as global to this module so that if a pub accidentally overwrites the entire // rubicon object, then we do not lose other data config.getConfig('rubicon', config => { - utils.mergeDeep(rubiConf, config.rubicon); + mergeDeep(rubiConf, config.rubicon); }); const GVLID = 52; @@ -122,7 +122,7 @@ var sizeMap = { 578: '980x552', 580: '505x656' }; -utils._each(sizeMap, (item, key) => sizeMap[item] = key); +_each(sizeMap, (item, key) => sizeMap[item] = key); export const spec = { code: 'rubicon', @@ -140,7 +140,7 @@ export const spec = { for (let i = 0, props = ['accountId', 'siteId', 'zoneId']; i < props.length; i++) { bid.params[props[i]] = parseInt(bid.params[props[i]]) if (isNaN(bid.params[props[i]])) { - utils.logError('Rubicon: wrong format of accountId or siteId or zoneId.') + logError('Rubicon: wrong format of accountId or siteId or zoneId.') return false } } @@ -180,7 +180,7 @@ export const spec = { ext: { [bidRequest.bidder]: bidRequest.params }, - video: utils.deepAccess(bidRequest, 'mediaTypes.video') || {} + video: deepAccess(bidRequest, 'mediaTypes.video') || {} }], ext: { prebid: { @@ -217,7 +217,7 @@ export const spec = { let modules = (getGlobal()).installedModules; if (modules && (!modules.length || modules.indexOf('rubiconAnalyticsAdapter') !== -1)) { - utils.deepSetValue(data, 'ext.prebid.analytics', {'rubicon': {'client-analytics': true}}); + deepSetValue(data, 'ext.prebid.analytics', {'rubicon': {'client-analytics': true}}); } let bidFloor; @@ -230,11 +230,11 @@ export const spec = { size: parseSizes(bidRequest, 'video') }); } catch (e) { - utils.logError('Rubicon: getFloor threw an error: ', e); + logError('Rubicon: getFloor threw an error: ', e); } bidFloor = typeof floorInfo === 'object' && floorInfo.currency === 'USD' && !isNaN(parseInt(floorInfo.floor)) ? parseFloat(floorInfo.floor) : undefined; } else { - bidFloor = parseFloat(utils.deepAccess(bidRequest, 'params.floor')); + bidFloor = parseFloat(deepAccess(bidRequest, 'params.floor')); } if (!isNaN(bidFloor)) { data.imp[0].bidfloor = bidFloor; @@ -253,36 +253,36 @@ export const spec = { gdprApplies = bidderRequest.gdprConsent.gdprApplies ? 1 : 0; } - utils.deepSetValue(data, 'regs.ext.gdpr', gdprApplies); - utils.deepSetValue(data, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(data, 'regs.ext.gdpr', gdprApplies); + deepSetValue(data, 'user.ext.consent', bidderRequest.gdprConsent.consentString); } if (bidderRequest.uspConsent) { - utils.deepSetValue(data, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(data, 'regs.ext.us_privacy', bidderRequest.uspConsent); } - const eids = utils.deepAccess(bidderRequest, 'bids.0.userIdAsEids'); + const eids = deepAccess(bidderRequest, 'bids.0.userIdAsEids'); if (eids && eids.length) { - utils.deepSetValue(data, 'user.ext.eids', eids); + deepSetValue(data, 'user.ext.eids', eids); } // set user.id value from config value const configUserId = config.getConfig('user.id'); if (configUserId) { - utils.deepSetValue(data, 'user.id', configUserId); + deepSetValue(data, 'user.id', configUserId); } if (config.getConfig('coppa') === true) { - utils.deepSetValue(data, 'regs.coppa', 1); + deepSetValue(data, 'regs.coppa', 1); } if (bidRequest.schain && hasValidSupplyChainParams(bidRequest.schain)) { - utils.deepSetValue(data, 'source.ext.schain', bidRequest.schain); + deepSetValue(data, 'source.ext.schain', bidRequest.schain); } const multibid = config.getConfig('multibid'); if (multibid) { - utils.deepSetValue(data, 'ext.prebid.multibid', multibid.reduce((result, i) => { + deepSetValue(data, 'ext.prebid.multibid', multibid.reduce((result, i) => { let obj = {}; Object.keys(i).forEach(key => { @@ -299,11 +299,11 @@ export const spec = { // if storedAuctionResponse has been set, pass SRID if (bidRequest.storedAuctionResponse) { - utils.deepSetValue(data.imp[0], 'ext.prebid.storedauctionresponse.id', bidRequest.storedAuctionResponse.toString()); + deepSetValue(data.imp[0], 'ext.prebid.storedauctionresponse.id', bidRequest.storedAuctionResponse.toString()); } // set ext.prebid.auctiontimestamp using auction time - utils.deepSetValue(data.imp[0], 'ext.prebid.auctiontimestamp', bidderRequest.auctionStart); + deepSetValue(data.imp[0], 'ext.prebid.auctiontimestamp', bidderRequest.auctionStart); return { method: 'POST', @@ -322,14 +322,14 @@ export const spec = { url: `https://${rubiConf.bannerHost || 'fastlane'}.rubiconproject.com/a/api/fastlane.json`, data: spec.getOrderedParams(bidParams).reduce((paramString, key) => { const propValue = bidParams[key]; - return ((utils.isStr(propValue) && propValue !== '') || utils.isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString; + return ((isStr(propValue) && propValue !== '') || isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString; }, '') + `slots=1&rand=${Math.random()}`, bidRequest }; })); } else { // single request requires bids to be grouped by site id into a single request - // note: utils.groupBy wasn't used because deep property access was needed + // note: groupBy wasn't used because deep property access was needed const nonVideoRequests = bidRequests.filter(bidRequest => bidType(bidRequest) === 'banner'); const groupedBidRequests = nonVideoRequests.reduce((groupedBids, bid) => { (groupedBids[bid.params['siteId']] = groupedBids[bid.params['siteId']] || []).push(bid); @@ -353,7 +353,7 @@ export const spec = { url: `https://${rubiConf.bannerHost || 'fastlane'}.rubiconproject.com/a/api/fastlane.json`, data: spec.getOrderedParams(combinedSlotParams).reduce((paramString, key) => { const propValue = combinedSlotParams[key]; - return ((utils.isStr(propValue) && propValue !== '') || utils.isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString; + return ((isStr(propValue) && propValue !== '') || isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString; }, '') + `slots=${bidsInGroup.length}&rand=${Math.random()}`, bidRequest: bidsInGroup }); @@ -485,7 +485,7 @@ export const spec = { size: '*' }); } catch (e) { - utils.logError('Rubicon: getFloor threw an error: ', e); + logError('Rubicon: getFloor threw an error: ', e); } data['rp_hard_floor'] = typeof floorInfo === 'object' && floorInfo.currency === 'USD' && !isNaN(parseInt(floorInfo.floor)) ? floorInfo.floor : undefined; } @@ -493,7 +493,7 @@ export const spec = { // add p_pos only if specified and valid // For SRA we need to explicitly put empty semi colons so AE treats it as empty, instead of copying the latter value let posMapping = {1: 'atf', 3: 'btf'}; - let pos = posMapping[utils.deepAccess(bidRequest, 'mediaTypes.banner.pos')] || ''; + let pos = posMapping[deepAccess(bidRequest, 'mediaTypes.banner.pos')] || ''; data['p_pos'] = (params.position === 'atf' || params.position === 'btf') ? params.position : pos; // pass publisher provided userId if configured @@ -532,7 +532,7 @@ export const spec = { } } } catch (e) { - utils.logWarn('Rubicon: error reading eid:', eid, e); + logWarn('Rubicon: error reading eid:', eid, e); } }); } @@ -605,9 +605,9 @@ export const spec = { // video response from PBS Java openRTB if (responseObj.seatbid) { - const responseErrors = utils.deepAccess(responseObj, 'ext.errors.rubicon'); + const responseErrors = deepAccess(responseObj, 'ext.errors.rubicon'); if (Array.isArray(responseErrors) && responseErrors.length > 0) { - utils.logWarn('Rubicon: Error in video response'); + logWarn('Rubicon: Error in video response'); } const bids = []; responseObj.seatbid.forEach(seatbid => { @@ -620,8 +620,8 @@ export const spec = { bidderCode: seatbid.seat, ttl: 300, netRevenue: rubiConf.netRevenue !== false, // If anything other than false, netRev is true - width: bid.w || utils.deepAccess(bidRequest, 'mediaTypes.video.w') || utils.deepAccess(bidRequest, 'params.video.playerWidth'), - height: bid.h || utils.deepAccess(bidRequest, 'mediaTypes.video.h') || utils.deepAccess(bidRequest, 'params.video.playerHeight'), + width: bid.w || deepAccess(bidRequest, 'mediaTypes.video.w') || deepAccess(bidRequest, 'params.video.playerWidth'), + height: bid.h || deepAccess(bidRequest, 'mediaTypes.video.h') || deepAccess(bidRequest, 'params.video.playerHeight'), }; if (bid.id) { @@ -633,22 +633,22 @@ export const spec = { } if (bid.adomain) { - utils.deepSetValue(bidObject, 'meta.advertiserDomains', Array.isArray(bid.adomain) ? bid.adomain : [bid.adomain]); + deepSetValue(bidObject, 'meta.advertiserDomains', Array.isArray(bid.adomain) ? bid.adomain : [bid.adomain]); } - if (utils.deepAccess(bid, 'ext.bidder.rp.advid')) { - utils.deepSetValue(bidObject, 'meta.advertiserId', bid.ext.bidder.rp.advid); + if (deepAccess(bid, 'ext.bidder.rp.advid')) { + deepSetValue(bidObject, 'meta.advertiserId', bid.ext.bidder.rp.advid); } - let serverResponseTimeMs = utils.deepAccess(responseObj, 'ext.responsetimemillis.rubicon'); + let serverResponseTimeMs = deepAccess(responseObj, 'ext.responsetimemillis.rubicon'); if (bidRequest && serverResponseTimeMs) { bidRequest.serverResponseTimeMs = serverResponseTimeMs; } - if (utils.deepAccess(bid, 'ext.prebid.type') === VIDEO) { + if (deepAccess(bid, 'ext.prebid.type') === VIDEO) { bidObject.mediaType = VIDEO; - utils.deepSetValue(bidObject, 'meta.mediaType', VIDEO); - const extPrebidTargeting = utils.deepAccess(bid, 'ext.prebid.targeting'); + deepSetValue(bidObject, 'meta.mediaType', VIDEO); + const extPrebidTargeting = deepAccess(bid, 'ext.prebid.targeting'); // If ext.prebid.targeting exists, add it as a property value named 'adserverTargeting' if (extPrebidTargeting && typeof extPrebidTargeting === 'object') { @@ -670,12 +670,12 @@ export const spec = { if (bid.nurl) { bidObject.vastUrl = bid.nurl; } if (!bidObject.vastUrl && bid.nurl) { bidObject.vastUrl = bid.nurl; } - const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); if (videoContext.toLowerCase() === 'outstream') { bidObject.renderer = outstreamRenderer(bidObject); } } else { - utils.logWarn('Rubicon: video response received non-video media type'); + logWarn('Rubicon: video response received non-video media type'); } bids.push(bidObject); @@ -754,7 +754,7 @@ export const spec = { bids.push(bid); } else { - utils.logError(`Rubicon: bidRequest undefined at index position:${i}`, bidRequest, responseObj); + logError(`Rubicon: bidRequest undefined at index position:${i}`, bidRequest, responseObj); } return bids; @@ -794,7 +794,7 @@ export const spec = { * @return {Object} params bid params */ transformBidParams: function(params, isOpenRtb) { - return utils.convertTypes({ + return convertTypes({ 'accountId': 'number', 'siteId': 'number', 'zoneId': 'number' @@ -885,7 +885,7 @@ function outstreamRenderer(rtbBid) { try { renderer.setRender(renderBid); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; @@ -900,7 +900,7 @@ function parseSizes(bid, mediaType) { params.video.playerWidth, params.video.playerHeight ]; - } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { + } else if (Array.isArray(deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; @@ -912,12 +912,12 @@ function parseSizes(bid, mediaType) { let sizes = []; if (Array.isArray(params.sizes)) { sizes = params.sizes; - } else if (typeof utils.deepAccess(bid, 'mediaTypes.banner.sizes') !== 'undefined') { + } else if (typeof deepAccess(bid, 'mediaTypes.banner.sizes') !== 'undefined') { sizes = mapSizes(bid.mediaTypes.banner.sizes); } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = mapSizes(bid.sizes) } else { - utils.logWarn('Rubicon: no sizes are setup or found'); + logWarn('Rubicon: no sizes are setup or found'); } return masSizeOrdering(sizes); @@ -984,16 +984,16 @@ function applyFPD(bidRequest, mediaType, data) { site: {ext: {data: {...bidRequest.params.inventory}}} }; - if (bidRequest.params.keywords) BID_FPD.site.keywords = (utils.isArray(bidRequest.params.keywords)) ? bidRequest.params.keywords.join(',') : bidRequest.params.keywords; + if (bidRequest.params.keywords) BID_FPD.site.keywords = (isArray(bidRequest.params.keywords)) ? bidRequest.params.keywords.join(',') : bidRequest.params.keywords; - let fpd = utils.mergeDeep({}, config.getConfig('ortb2') || {}, BID_FPD); - let impData = utils.deepAccess(bidRequest.ortb2Imp, 'ext.data') || {}; + let fpd = mergeDeep({}, config.getConfig('ortb2') || {}, BID_FPD); + let impData = deepAccess(bidRequest.ortb2Imp, 'ext.data') || {}; const SEGTAX = {user: [4], site: [1, 2, 5, 6]}; const MAP = {user: 'tg_v.', site: 'tg_i.', adserver: 'tg_i.dfp_ad_unit_code', pbadslot: 'tg_i.pbadslot', keywords: 'kw'}; const validate = function(prop, key, parentName) { if (key === 'data' && Array.isArray(prop)) { - return prop.filter(name => name.segment && utils.deepAccess(name, 'ext.segtax') && SEGTAX[parentName] && - SEGTAX[parentName].indexOf(utils.deepAccess(name, 'ext.segtax')) !== -1).map(value => { + return prop.filter(name => name.segment && deepAccess(name, 'ext.segtax') && SEGTAX[parentName] && + SEGTAX[parentName].indexOf(deepAccess(name, 'ext.segtax')) !== -1).map(value => { let segments = value.segment.filter(obj => obj.id).reduce((result, obj) => { result.push(obj.id); return result; @@ -1001,12 +1001,12 @@ function applyFPD(bidRequest, mediaType, data) { if (segments.length > 0) return segments.toString(); }).toString(); } else if (typeof prop === 'object' && !Array.isArray(prop)) { - utils.logWarn('Rubicon: Filtered FPD key: ', key, ': Expected value to be string, integer, or an array of strings/ints'); + logWarn('Rubicon: Filtered FPD key: ', key, ': Expected value to be string, integer, or an array of strings/ints'); } else if (typeof prop !== 'undefined') { return (Array.isArray(prop)) ? prop.filter(value => { if (typeof value !== 'object' && typeof value !== 'undefined') return value.toString(); - utils.logWarn('Rubicon: Filtered value: ', value, 'for key', key, ': Expected value to be string, integer, or an array of strings/ints'); + logWarn('Rubicon: Filtered value: ', value, 'for key', key, ': Expected value to be string, integer, or an array of strings/ints'); }).toString() : prop.toString(); } }; @@ -1045,10 +1045,10 @@ function applyFPD(bidRequest, mediaType, data) { }); } else { if (Object.keys(impData).length) { - utils.mergeDeep(data.imp[0].ext, {data: impData}); + mergeDeep(data.imp[0].ext, {data: impData}); } - utils.mergeDeep(data, fpd); + mergeDeep(data, fpd); } } @@ -1057,7 +1057,7 @@ function applyFPD(bidRequest, mediaType, data) { * @returns {*} */ function mapSizes(sizes) { - return utils.parseSizesInput(sizes) + return parseSizesInput(sizes) // map sizes while excluding non-matches .reduce((result, size) => { let mappedSize = parseInt(sizeMap[size], 10); @@ -1075,10 +1075,10 @@ function mapSizes(sizes) { * @returns {boolean} */ export function hasVideoMediaType(bidRequest) { - if (typeof utils.deepAccess(bidRequest, 'params.video') !== 'object') { + if (typeof deepAccess(bidRequest, 'params.video') !== 'object') { return false; } - return (typeof utils.deepAccess(bidRequest, `mediaTypes.${VIDEO}`) !== 'undefined'); + return (typeof deepAccess(bidRequest, `mediaTypes.${VIDEO}`) !== 'undefined'); } /** @@ -1092,9 +1092,9 @@ function bidType(bid, log = false) { if (hasVideoMediaType(bid)) { // Removed legacy mediaType support. new way using mediaTypes.video object is now required // We require either context as instream or outstream - if (['outstream', 'instream'].indexOf(utils.deepAccess(bid, `mediaTypes.${VIDEO}.context`)) === -1) { + if (['outstream', 'instream'].indexOf(deepAccess(bid, `mediaTypes.${VIDEO}.context`)) === -1) { if (log) { - utils.logError('Rubicon: mediaTypes.video.context must be outstream or instream'); + logError('Rubicon: mediaTypes.video.context must be outstream or instream'); } return; } @@ -1102,13 +1102,13 @@ function bidType(bid, log = false) { // we require playerWidth and playerHeight to come from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes if (parseSizes(bid, 'video').length < 2) { if (log) { - utils.logError('Rubicon: could not determine the playerSize of the video'); + logError('Rubicon: could not determine the playerSize of the video'); } return; } if (log) { - utils.logMessage('Rubicon: making video request for adUnit', bid.adUnitCode); + logMessage('Rubicon: making video request for adUnit', bid.adUnitCode); } return 'video'; } else { @@ -1116,14 +1116,14 @@ function bidType(bid, log = false) { // if we cannot determine them, we reject it! if (parseSizes(bid, 'banner').length === 0) { if (log) { - utils.logError('Rubicon: could not determine the sizes for banner request'); + logError('Rubicon: could not determine the sizes for banner request'); } return; } // everything looks good for banner so lets do it if (log) { - utils.logMessage('Rubicon: making banner request for adUnit', bid.adUnitCode); + logMessage('Rubicon: making banner request for adUnit', bid.adUnitCode); } return 'banner'; } @@ -1155,13 +1155,13 @@ export function masSizeOrdering(sizes) { export function determineRubiconVideoSizeId(bid) { // If we have size_id in the bid then use it - let rubiconSizeId = parseInt(utils.deepAccess(bid, 'params.video.size_id')); + let rubiconSizeId = parseInt(deepAccess(bid, 'params.video.size_id')); if (!isNaN(rubiconSizeId)) { return rubiconSizeId; } // otherwise 203 for outstream and 201 for instream // When this function is used we know it has to be one of outstream or instream - return utils.deepAccess(bid, `mediaTypes.${VIDEO}.context`) === 'outstream' ? 203 : 201; + return deepAccess(bid, `mediaTypes.${VIDEO}.context`) === 'outstream' ? 203 : 201; } /** @@ -1204,9 +1204,9 @@ export function hasValidVideoParams(bid) { } // loop through each param and verify it has the correct Object.keys(requiredParams).forEach(function(param) { - if (Object.prototype.toString.call(utils.deepAccess(bid, 'mediaTypes.video.' + param)) !== requiredParams[param]) { + if (Object.prototype.toString.call(deepAccess(bid, 'mediaTypes.video.' + param)) !== requiredParams[param]) { isValid = false; - utils.logError('Rubicon: mediaTypes.video.' + param + ' is required and must be of type: ' + requiredParams[param]); + logError('Rubicon: mediaTypes.video.' + param + ' is required and must be of type: ' + requiredParams[param]); } }) return isValid; @@ -1225,7 +1225,7 @@ export function hasValidSupplyChainParams(schain) { if (!status) return status; return requiredFields.every(field => node.hasOwnProperty(field)); }, true); - if (!isValid) utils.logError('Rubicon: required schain params missing'); + if (!isValid) logError('Rubicon: required schain params missing'); return isValid; } diff --git a/modules/scaleableAnalyticsAdapter.js b/modules/scaleableAnalyticsAdapter.js index 955a08c065a..d7379462e0d 100644 --- a/modules/scaleableAnalyticsAdapter.js +++ b/modules/scaleableAnalyticsAdapter.js @@ -4,7 +4,7 @@ import { ajax } from '../src/ajax.js'; import CONSTANTS from '../src/constants.json'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; +import { logMessage } from '../src/utils.js'; // Object.entries polyfill const entries = Object.entries || function(obj) { @@ -62,7 +62,7 @@ scaleableAnalytics.enableAnalytics = config => { scaleableAnalytics.originEnableAnalytics(config); scaleableAnalytics.enableAnalytics = function _enable() { - return utils.logMessage(`Analytics adapter for "${global}" already enabled, unnecessary call to \`enableAnalytics\`.`); + return logMessage(`Analytics adapter for "${global}" already enabled, unnecessary call to \`enableAnalytics\`.`); }; } diff --git a/modules/seedingAllianceBidAdapter.js b/modules/seedingAllianceBidAdapter.js index 258830d422a..00f3b64fb44 100755 --- a/modules/seedingAllianceBidAdapter.js +++ b/modules/seedingAllianceBidAdapter.js @@ -3,7 +3,7 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { NATIVE } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { _map, deepSetValue, isEmpty, deepAccess } from '../src/utils.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'seedingAlliance'; @@ -65,7 +65,7 @@ export const spec = { let url = bidderRequest.refererInfo.referer; const imp = validBidRequests.map((bid, id) => { - const assets = utils._map(bid.nativeParams, (bidParams, key) => { + const assets = _map(bid.nativeParams, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { @@ -130,8 +130,8 @@ export const spec = { }; if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(request, 'regs.ext.gdpr', (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean' && bidderRequest.gdprConsent.gdprApplies) ? 1 : 0); + deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(request, 'regs.ext.gdpr', (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean' && bidderRequest.gdprConsent.gdprApplies) ? 1 : 0); } return { @@ -146,7 +146,7 @@ export const spec = { }, interpretResponse: function(serverResponse, { bids }) { - if (utils.isEmpty(serverResponse.body)) { + if (isEmpty(serverResponse.body)) { return []; } @@ -219,7 +219,7 @@ function parseNative(bid) { function setOnAny(collection, key) { for (let i = 0, result; i < collection.length; i++) { - result = utils.deepAccess(collection[i], key); + result = deepAccess(collection[i], key); if (result) { return result; }