From 33762d1ee5abd0363e2b35fbbb07cb2d38287972 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 12 Sep 2019 16:38:12 -0700 Subject: [PATCH 01/19] 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/19] 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/19] 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/19] 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/19] 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 cf15276ad976914d180f0e2f10636392f346231b Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 17:58:41 -0700 Subject: [PATCH 06/19] adloader: not importing * from utils --- src/adloader.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/adloader.js b/src/adloader.js index 5460cc79410..9039fa14c4c 100644 --- a/src/adloader.js +++ b/src/adloader.js @@ -1,5 +1,5 @@ import includes from 'core-js-pure/features/array/includes.js'; -import * as utils from './utils.js'; +import { logError, logWarn, insertElement } from './utils.js'; const _requestCache = {}; // The below list contains modules or vendors whom Prebid allows to load external JS. @@ -20,11 +20,11 @@ const _approvedLoadExternalJSList = [ */ export function loadExternalScript(url, moduleCode, callback) { if (!moduleCode || !url) { - utils.logError('cannot load external script without url and moduleCode'); + logError('cannot load external script without url and moduleCode'); return; } if (!includes(_approvedLoadExternalJSList, moduleCode)) { - utils.logError(`${moduleCode} not whitelisted for loading external JavaScript`); + logError(`${moduleCode} not whitelisted for loading external JavaScript`); return; } // only load each asset once @@ -49,7 +49,7 @@ export function loadExternalScript(url, moduleCode, callback) { _requestCache[url].callbacks.push(callback); } - utils.logWarn(`module ${moduleCode} is loading external JavaScript`); + logWarn(`module ${moduleCode} is loading external JavaScript`); return requestResource(url, function () { _requestCache[url].loaded = true; try { @@ -57,7 +57,7 @@ export function loadExternalScript(url, moduleCode, callback) { _requestCache[url].callbacks[i](); } } catch (e) { - utils.logError('Error executing callback', 'adloader.js:loadExternalScript', e); + logError('Error executing callback', 'adloader.js:loadExternalScript', e); } }); @@ -84,7 +84,7 @@ export function loadExternalScript(url, moduleCode, callback) { jptScript.src = tagSrc; // add the new script tag to the page - utils.insertElement(jptScript); + insertElement(jptScript); return jptScript; } From a2f32c9c309963beca63111f73c8cc0535fc738e Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 18:05:18 -0700 Subject: [PATCH 07/19] ajax: not importing * from utils --- src/ajax.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/ajax.js b/src/ajax.js index a6317e7963d..5e926f3210d 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -1,6 +1,5 @@ import { config } from './config.js'; - -var utils = require('./utils.js'); +import { logMessage, logError, parseUrl, buildUrl, _each } from './utils.js'; const XHR_DONE = 4; @@ -25,10 +24,10 @@ export function ajaxBuilder(timeout = 3000, {request, done} = {}) { let callbacks = typeof callback === 'object' && callback !== null ? callback : { success: function() { - utils.logMessage('xhr success'); + logMessage('xhr success'); }, error: function(e) { - utils.logError('xhr error', null, e); + logError('xhr error', null, e); } }; @@ -55,14 +54,14 @@ export function ajaxBuilder(timeout = 3000, {request, done} = {}) { // Disabled timeout temporarily to avoid xhr failed requests. https://github.com/prebid/Prebid.js/issues/2648 if (!config.getConfig('disableAjaxTimeout')) { x.ontimeout = function () { - utils.logError(' xhr timeout after ', x.timeout, 'ms'); + logError(' xhr timeout after ', x.timeout, 'ms'); }; } if (method === 'GET' && data) { - let urlInfo = utils.parseUrl(url, options); + let urlInfo = parseUrl(url, options); Object.assign(urlInfo.search, data); - url = utils.buildUrl(urlInfo); + url = buildUrl(urlInfo); } x.open(method, url, true); @@ -75,7 +74,7 @@ export function ajaxBuilder(timeout = 3000, {request, done} = {}) { if (options.withCredentials) { x.withCredentials = true; } - utils._each(options.customHeaders, (value, header) => { + _each(options.customHeaders, (value, header) => { x.setRequestHeader(header, value); }); if (options.preflight) { @@ -93,7 +92,7 @@ export function ajaxBuilder(timeout = 3000, {request, done} = {}) { x.send(); } } catch (error) { - utils.logError('xhr construction', error); + logError('xhr construction', error); typeof callback === 'object' && callback !== null && callback.error(error); } } From 76efe51ed2816d2956a2da8170bcabadc7ad3246 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 18:10:17 -0700 Subject: [PATCH 08/19] AnalyticsAdapter: not importing * from utils --- src/AnalyticsAdapter.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/AnalyticsAdapter.js b/src/AnalyticsAdapter.js index 97513b80cc7..2c27307ead3 100644 --- a/src/AnalyticsAdapter.js +++ b/src/AnalyticsAdapter.js @@ -1,8 +1,8 @@ import CONSTANTS from './constants.json'; import { ajax } from './ajax.js'; +import { logMessage, _each } from './utils.js'; const events = require('./events.js'); -const utils = require('./utils.js'); const { EVENTS: { @@ -123,22 +123,22 @@ export default function AnalyticsAdapter({ url, analyticsType, global, handler } } }; - utils._each(_handlers, (handler, event) => { + _each(_handlers, (handler, event) => { events.on(event, handler); }); } else { - utils.logMessage(`Analytics adapter for "${global}" disabled by sampling`); + logMessage(`Analytics adapter for "${global}" disabled by sampling`); } // finally set this function to return log message, prevents multiple adapter listeners this._oldEnable = this.enableAnalytics; this.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\`.`); }; } function _disable() { - utils._each(_handlers, (handler, event) => { + _each(_handlers, (handler, event) => { events.off(event, handler); }); this.enableAnalytics = this._oldEnable ? this._oldEnable : _enable; @@ -158,6 +158,6 @@ export default function AnalyticsAdapter({ url, analyticsType, global, handler } _enableCheck = false; } - utils.logMessage(`event count sent to ${global}: ${_eventCount}`); + logMessage(`event count sent to ${global}: ${_eventCount}`); } } From c1d8d73f1198257bb7ca837bb36a01ec3c04066d Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 18:26:17 -0700 Subject: [PATCH 09/19] adapterManager: not importing * from utils --- src/adapterManager.js | 87 ++++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 42 deletions(-) diff --git a/src/adapterManager.js b/src/adapterManager.js index 5f8f2e5721c..9a3d05a4321 100644 --- a/src/adapterManager.js +++ b/src/adapterManager.js @@ -1,6 +1,10 @@ /** @module adaptermanger */ -import { flatten, getBidderCodes, getDefinedParams, shuffle, timestamp, getBidderRequest, bind } from './utils.js'; +import { + _each, getUserConfiguredParams, groupBy, logInfo, deepAccess, isValidMediaTypes, + getUniqueIdentifierStr, deepClone, logWarn, logError, logMessage, isArray, generateUUID, + flatten, getBidderCodes, getDefinedParams, shuffle, timestamp, getBidderRequest, bind +} from './utils.js'; import { getLabels, resolveStatus } from './sizeMapping.js'; import { processNativeAdUnitParams, nativeAdapters } from './native.js'; import { newBidder } from './adapters/bidderFactory.js'; @@ -12,7 +16,6 @@ import find from 'core-js-pure/features/array/find.js'; import { adunitCounter } from './adUnits.js'; import { getRefererInfo } from './refererDetection.js'; -var utils = require('./utils.js'); var CONSTANTS = require('./constants.json'); var events = require('./events.js'); let s2sTestingModule; // store s2sTesting module if it's loaded @@ -25,7 +28,7 @@ let _aliasRegistry = adapterManager.aliasRegistry = {}; let _s2sConfigs = []; config.getConfig('s2sConfig', config => { if (config && config.s2sConfig) { - _s2sConfigs = Array.isArray(config.s2sConfig) ? config.s2sConfig : [config.s2sConfig]; + _s2sConfigs = isArray(config.s2sConfig) ? config.s2sConfig : [config.s2sConfig]; } }); @@ -51,16 +54,16 @@ function getBids({bidderCode, auctionId, bidderRequestId, adUnits, labels, src}) ); if (!active) { - utils.logInfo(`Size mapping disabled adUnit "${adUnit.code}"`); + logInfo(`Size mapping disabled adUnit "${adUnit.code}"`); } else if (filterResults) { - utils.logInfo(`Size mapping filtered adUnit "${adUnit.code}" banner sizes from `, filterResults.before, 'to ', filterResults.after); + logInfo(`Size mapping filtered adUnit "${adUnit.code}" banner sizes from `, filterResults.before, 'to ', filterResults.after); } if (active) { result.push(adUnit.bids.filter(bid => bid.bidder === bidderCode) .reduce((bids, bid) => { const nativeParams = - adUnit.nativeParams || utils.deepAccess(adUnit, 'mediaTypes.native'); + adUnit.nativeParams || deepAccess(adUnit, 'mediaTypes.native'); if (nativeParams) { bid = Object.assign({}, bid, { nativeParams: processNativeAdUnitParams(nativeParams), @@ -81,17 +84,17 @@ function getBids({bidderCode, auctionId, bidderRequestId, adUnits, labels, src}) } = resolveStatus(getLabels(bid, labels), filteredMediaTypes); if (!active) { - utils.logInfo(`Size mapping deactivated adUnit "${adUnit.code}" bidder "${bid.bidder}"`); + logInfo(`Size mapping deactivated adUnit "${adUnit.code}" bidder "${bid.bidder}"`); } else if (filterResults) { - utils.logInfo(`Size mapping filtered adUnit "${adUnit.code}" bidder "${bid.bidder}" banner sizes from `, filterResults.before, 'to ', filterResults.after); + logInfo(`Size mapping filtered adUnit "${adUnit.code}" bidder "${bid.bidder}" banner sizes from `, filterResults.before, 'to ', filterResults.after); } - if (utils.isValidMediaTypes(mediaTypes)) { + if (isValidMediaTypes(mediaTypes)) { bid = Object.assign({}, bid, { mediaTypes }); } else { - utils.logError( + logError( `mediaTypes is not correctly configured for adunit ${adUnit.code}` ); } @@ -100,8 +103,8 @@ function getBids({bidderCode, auctionId, bidderRequestId, adUnits, labels, src}) bids.push(Object.assign({}, bid, { adUnitCode: adUnit.code, transactionId: adUnit.transactionId, - sizes: utils.deepAccess(mediaTypes, 'banner.sizes') || utils.deepAccess(mediaTypes, 'video.playerSize') || [], - bidId: bid.bid_id || utils.getUniqueIdentifierStr(), + sizes: deepAccess(mediaTypes, 'banner.sizes') || deepAccess(mediaTypes, 'video.playerSize') || [], + bidId: bid.bid_id || getUniqueIdentifierStr(), bidderRequestId, auctionId, src, @@ -122,7 +125,7 @@ const hookedGetBids = hook('sync', getBids, 'getBids'); function getAdUnitCopyForPrebidServer(adUnits, s2sConfig) { let adaptersServerSide = s2sConfig.bidders; - let adUnitsCopy = utils.deepClone(adUnits); + let adUnitsCopy = deepClone(adUnits); adUnitsCopy.forEach((adUnit) => { // filter out client side bids @@ -130,7 +133,7 @@ function getAdUnitCopyForPrebidServer(adUnits, s2sConfig) { return includes(adaptersServerSide, bid.bidder) && (!doingS2STesting(s2sConfig) || bid.finalSource !== s2sTestingModule.CLIENT); }).map((bid) => { - bid.bid_id = utils.getUniqueIdentifierStr(); + bid.bid_id = getUniqueIdentifierStr(); return bid; }); }); @@ -143,7 +146,7 @@ function getAdUnitCopyForPrebidServer(adUnits, s2sConfig) { } function getAdUnitCopyForClientAdapters(adUnits) { - let adUnitsClientCopy = utils.deepClone(adUnits); + let adUnitsClientCopy = deepClone(adUnits); // filter out s2s bids adUnitsClientCopy.forEach((adUnit) => { adUnit.bids = adUnit.bids.filter((bid) => { @@ -254,20 +257,20 @@ adapterManager.makeBidRequests = hook('sync', function (adUnits, auctionStart, a _s2sConfigs.forEach(s2sConfig => { if (s2sConfig && s2sConfig.enabled) { if ((isTestingServerOnly(s2sConfig) && adUnitsContainServerRequests(adUnits, s2sConfig))) { - utils.logWarn('testServerOnly: True. All client requests will be suppressed.'); + logWarn('testServerOnly: True. All client requests will be suppressed.'); clientBidderCodes.length = 0; } let adUnitsS2SCopy = getAdUnitCopyForPrebidServer(adUnits, s2sConfig); - let tid = utils.generateUUID(); + let tid = generateUUID(); adaptersServerSide.forEach(bidderCode => { - const bidderRequestId = utils.getUniqueIdentifierStr(); + const bidderRequestId = getUniqueIdentifierStr(); const bidderRequest = { bidderCode, auctionId, bidderRequestId, tid, - bids: hookedGetBids({bidderCode, auctionId, bidderRequestId, 'adUnits': utils.deepClone(adUnitsS2SCopy), labels, src: CONSTANTS.S2S.SRC}), + bids: hookedGetBids({bidderCode, auctionId, bidderRequestId, 'adUnits': deepClone(adUnitsS2SCopy), labels, src: CONSTANTS.S2S.SRC}), auctionStart: auctionStart, timeout: s2sConfig.timeout, src: CONSTANTS.S2S.SRC, @@ -298,19 +301,19 @@ adapterManager.makeBidRequests = hook('sync', function (adUnits, auctionStart, a // client adapters let adUnitsClientCopy = getAdUnitCopyForClientAdapters(adUnits); clientBidderCodes.forEach(bidderCode => { - const bidderRequestId = utils.getUniqueIdentifierStr(); + const bidderRequestId = getUniqueIdentifierStr(); const bidderRequest = { bidderCode, auctionId, bidderRequestId, - bids: hookedGetBids({bidderCode, auctionId, bidderRequestId, 'adUnits': utils.deepClone(adUnitsClientCopy), labels, src: 'client'}), + bids: hookedGetBids({bidderCode, auctionId, bidderRequestId, 'adUnits': deepClone(adUnitsClientCopy), labels, src: 'client'}), auctionStart: auctionStart, timeout: cbTimeout, refererInfo }; const adapter = _bidderRegistry[bidderCode]; if (!adapter) { - utils.logError(`Trying to make a request for bidder that does not exist: ${bidderCode}`); + logError(`Trying to make a request for bidder that does not exist: ${bidderCode}`); } if (adapter && bidderRequest.bids && bidderRequest.bids.length !== 0) { @@ -334,7 +337,7 @@ adapterManager.makeBidRequests = hook('sync', function (adUnits, auctionStart, a adapterManager.callBids = (adUnits, bidRequests, addBidResponse, doneCb, requestCallbacks, requestBidsTimeout, onTimelyResponse) => { if (!bidRequests.length) { - utils.logWarn('callBids executed with no bidRequests. Were they filtered by labels or sizing?'); + logWarn('callBids executed with no bidRequests. Were they filtered by labels or sizing?'); return; } @@ -384,7 +387,7 @@ adapterManager.callBids = (adUnits, bidRequests, addBidResponse, doneCb, request let allBidders = s2sBidRequest.ad_units.reduce((adapters, adUnit) => { return adapters.concat((adUnit.bids || []).reduce((adapters, bid) => adapters.concat(bid.bidder), [])); }, []); - utils.logMessage(`CALLING S2S HEADER BIDDERS ==== ${adaptersServerSide.filter(adapter => includes(allBidders, adapter)).join(',')}`); + logMessage(`CALLING S2S HEADER BIDDERS ==== ${adaptersServerSide.filter(adapter => includes(allBidders, adapter)).join(',')}`); // fire BID_REQUESTED event for each s2s bidRequest uniqueServerRequests.forEach(bidRequest => { @@ -406,7 +409,7 @@ adapterManager.callBids = (adUnits, bidRequests, addBidResponse, doneCb, request ); } } else { - utils.logError('missing ' + s2sConfig.adapter); + logError('missing ' + s2sConfig.adapter); } counter++ } @@ -418,7 +421,7 @@ adapterManager.callBids = (adUnits, bidRequests, addBidResponse, doneCb, request // TODO : Do we check for bid in pool from here and skip calling adapter again ? const adapter = _bidderRegistry[bidRequest.bidderCode]; config.runWithBidder(bidRequest.bidderCode, () => { - utils.logMessage(`CALLING BIDDER`); + logMessage(`CALLING BIDDER`); events.emit(CONSTANTS.EVENTS.BID_REQUESTED, bidRequest); }); let ajax = ajaxBuilder(requestBidsTimeout, requestCallbacks ? { @@ -441,7 +444,7 @@ adapterManager.callBids = (adUnits, bidRequests, addBidResponse, doneCb, request ) ); } catch (e) { - utils.logError(`${bidRequest.bidderCode} Bid Adapter emitted an uncaught error when parsing their bidRequest`, {e, bidRequest}); + logError(`${bidRequest.bidderCode} Bid Adapter emitted an uncaught error when parsing their bidRequest`, {e, bidRequest}); adapterDone(); } }); @@ -476,10 +479,10 @@ adapterManager.registerBidAdapter = function (bidAdapter, bidderCode, {supported nativeAdapters.push(bidderCode); } } else { - utils.logError('Bidder adaptor error for bidder code: ' + bidderCode + 'bidder must implement a callBids() function'); + logError('Bidder adaptor error for bidder code: ' + bidderCode + 'bidder must implement a callBids() function'); } } else { - utils.logError('bidAdapter or bidderCode not specified'); + logError('bidAdapter or bidderCode not specified'); } }; @@ -502,7 +505,7 @@ adapterManager.aliasBidAdapter = function (bidderCode, alias, options) { } }); nonS2SAlias.forEach(bidderCode => { - utils.logError('bidderCode "' + bidderCode + '" is not an existing bidder.', 'adapterManager.aliasBidAdapter'); + logError('bidderCode "' + bidderCode + '" is not an existing bidder.', 'adapterManager.aliasBidAdapter'); }) } else { try { @@ -524,11 +527,11 @@ adapterManager.aliasBidAdapter = function (bidderCode, alias, options) { supportedMediaTypes }); } catch (e) { - utils.logError(bidderCode + ' bidder does not currently support aliasing.', 'adapterManager.aliasBidAdapter'); + logError(bidderCode + ' bidder does not currently support aliasing.', 'adapterManager.aliasBidAdapter'); } } } else { - utils.logMessage('alias name "' + alias + '" has been already specified.'); + logMessage('alias name "' + alias + '" has been already specified.'); } }; @@ -538,25 +541,25 @@ adapterManager.registerAnalyticsAdapter = function ({adapter, code, gvlid}) { adapter.code = code; _analyticsRegistry[code] = { adapter, gvlid }; } else { - utils.logError(`Prebid Error: Analytics adaptor error for analytics "${code}" + logError(`Prebid Error: Analytics adaptor error for analytics "${code}" analytics adapter must implement an enableAnalytics() function`); } } else { - utils.logError('Prebid Error: analyticsAdapter or analyticsCode not specified'); + logError('Prebid Error: analyticsAdapter or analyticsCode not specified'); } }; adapterManager.enableAnalytics = function (config) { - if (!utils.isArray(config)) { + if (!isArray(config)) { config = [config]; } - utils._each(config, adapterConfig => { + _each(config, adapterConfig => { var adapter = _analyticsRegistry[adapterConfig.provider].adapter; if (adapter) { adapter.enableAnalytics(adapterConfig); } else { - utils.logError(`Prebid Error: no analytics adapter found in registry for + logError(`Prebid Error: no analytics adapter found in registry for ${adapterConfig.provider}.`); } }); @@ -581,22 +584,22 @@ function tryCallBidderMethod(bidder, method, param) { const adapter = _bidderRegistry[bidder]; const spec = adapter.getSpec(); if (spec && spec[method] && typeof spec[method] === 'function') { - utils.logInfo(`Invoking ${bidder}.${method}`); + logInfo(`Invoking ${bidder}.${method}`); config.runWithBidder(bidder, bind.call(spec[method], spec, param)); } } catch (e) { - utils.logWarn(`Error calling ${method} of ${bidder}`); + logWarn(`Error calling ${method} of ${bidder}`); } } adapterManager.callTimedOutBidders = function(adUnits, timedOutBidders, cbTimeout) { timedOutBidders = timedOutBidders.map((timedOutBidder) => { // Adding user configured params & timeout to timeout event data - timedOutBidder.params = utils.getUserConfiguredParams(adUnits, timedOutBidder.adUnitCode, timedOutBidder.bidder); + timedOutBidder.params = getUserConfiguredParams(adUnits, timedOutBidder.adUnitCode, timedOutBidder.bidder); timedOutBidder.timeout = cbTimeout; return timedOutBidder; }); - timedOutBidders = utils.groupBy(timedOutBidders, 'bidder'); + timedOutBidders = groupBy(timedOutBidders, 'bidder'); Object.keys(timedOutBidders).forEach((bidder) => { tryCallBidderMethod(bidder, 'onTimeout', timedOutBidders[bidder]); @@ -605,7 +608,7 @@ adapterManager.callTimedOutBidders = function(adUnits, timedOutBidders, cbTimeou adapterManager.callBidWonBidder = function(bidder, bid, adUnits) { // Adding user configured params to bidWon event data - bid.params = utils.getUserConfiguredParams(adUnits, bid.adUnitCode, bid.bidder); + bid.params = getUserConfiguredParams(adUnits, bid.adUnitCode, bid.bidder); adunitCounter.incrementBidderWinsCounter(bid.adUnitCode, bid.bidder); tryCallBidderMethod(bidder, 'onBidWon', bid); }; From 9f9245b6a7b52f2ade5f2fd5c910efc99c33a287 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 18:45:47 -0700 Subject: [PATCH 10/19] auction: not importing * from utils --- src/auction.js | 49 ++++++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/auction.js b/src/auction.js index a6f0342e582..498f08d6c73 100644 --- a/src/auction.js +++ b/src/auction.js @@ -57,7 +57,10 @@ * @property {function(): void} callBids - sends requests to all adapters for bids */ -import {flatten, timestamp, adUnitsFilter, deepAccess, getBidRequest, getValue, parseUrl} from './utils.js'; +import { + flatten, timestamp, adUnitsFilter, deepAccess, getBidRequest, getValue, parseUrl, generateUUID, + logMessage, bind, logError, logInfo, logWarn, isEmpty, _each, isFn, isEmptyStr +} from './utils.js'; import { getPriceBucketString } from './cpmBucketManager.js'; import { getNativeTargeting } from './native.js'; import { getCacheUrl, store } from './videoCache.js'; @@ -71,7 +74,7 @@ import { OUTSTREAM } from './video.js'; import { VIDEO } from './mediaTypes.js'; const { syncUsers } = userSync; -const utils = require('./utils.js'); + const adapterManager = require('./adapterManager.js').default; const events = require('./events.js'); const CONSTANTS = require('./constants.json'); @@ -112,7 +115,7 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a let _noBids = []; let _auctionStart; let _auctionEnd; - let _auctionId = auctionId || utils.generateUUID(); + let _auctionId = auctionId || generateUUID(); let _auctionStatus; let _callback = callback; let _timer; @@ -157,7 +160,7 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a if (_auctionEnd === undefined) { let timedOutBidders = []; if (timedOut) { - utils.logMessage(`Auction ${_auctionId} timedOut`); + logMessage(`Auction ${_auctionId} timedOut`); timedOutBidders = getTimedOutBids(_bidderRequests, _timelyBidders); if (timedOutBidders.length) { events.emit(CONSTANTS.EVENTS.BID_TIMEOUT, timedOutBidders); @@ -173,13 +176,13 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a if (_callback != null) { const adUnitCodes = _adUnitCodes; const bids = _bidsReceived - .filter(utils.bind.call(adUnitsFilter, this, adUnitCodes)) + .filter(bind.call(adUnitsFilter, this, adUnitCodes)) .reduce(groupByPlacement, {}); _callback.apply($$PREBID_GLOBAL$$, [bids, timedOut, _auctionId]); _callback = null; } } catch (e) { - utils.logError('Error executing bidsBackHandler', null, e); + logError('Error executing bidsBackHandler', null, e); } finally { // Calling timed out bidders if (timedOutBidders.length) { @@ -199,7 +202,7 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a function auctionDone() { config.resetBidder(); // when all bidders have called done callback atleast once it means auction is complete - utils.logInfo(`Bids Received for Auction with id: ${_auctionId}`, _bidsReceived); + logInfo(`Bids Received for Auction with id: ${_auctionId}`, _bidsReceived); _auctionStatus = AUCTION_COMPLETED; executeCallback(false, true); } @@ -213,10 +216,10 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a _auctionStart = Date.now(); let bidRequests = adapterManager.makeBidRequests(_adUnits, _auctionStart, _auctionId, _timeout, _labels); - utils.logInfo(`Bids Requested for Auction with id: ${_auctionId}`, bidRequests); + logInfo(`Bids Requested for Auction with id: ${_auctionId}`, bidRequests); if (bidRequests.length < 1) { - utils.logWarn('No valid bid requests returned for auction'); + logWarn('No valid bid requests returned for auction'); auctionDone(); } else { addBidderRequests.call({ @@ -279,7 +282,7 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a }; if (!runIfOriginHasCapacity(call)) { - utils.logWarn('queueing auction due to limited endpoint capacity'); + logWarn('queueing auction due to limited endpoint capacity'); queuedCalls.push(call); } @@ -404,7 +407,7 @@ export function auctionCallbacks(auctionDone, auctionInstance) { bidderRequestsDone.add(bidderRequest); - if (auctionOptionsConfig && !utils.isEmpty(auctionOptionsConfig)) { + if (auctionOptionsConfig && !isEmpty(auctionOptionsConfig)) { const secondaryBidders = auctionOptionsConfig.secondaryBidders; if (secondaryBidders && !bidderRequests.every(bidder => includes(secondaryBidders, bidder.bidderCode))) { bidderRequests = bidderRequests.filter(request => !includes(secondaryBidders, request.bidderCode)); @@ -463,7 +466,7 @@ function tryAddVideoBid(auctionInstance, bidResponse, bidRequests, afterBidAdded addBid = false; callPrebidCache(auctionInstance, bidResponse, afterBidAdded, bidderRequest); } else if (!bidResponse.vastUrl) { - utils.logError('videoCacheKey specified but not required vastUrl for video bid'); + logError('videoCacheKey specified but not required vastUrl for video bid'); addBid = false; } } @@ -476,12 +479,12 @@ function tryAddVideoBid(auctionInstance, bidResponse, bidRequests, afterBidAdded export const callPrebidCache = hook('async', function(auctionInstance, bidResponse, afterBidAdded, bidderRequest) { store([bidResponse], function (error, cacheIds) { if (error) { - utils.logWarn(`Failed to save to the video cache: ${error}. Video bid must be discarded.`); + logWarn(`Failed to save to the video cache: ${error}. Video bid must be discarded.`); doCallbacksIfTimedout(auctionInstance, bidResponse); } else { if (cacheIds[0].uuid === '') { - utils.logWarn(`Supplied video cache key was already in use by Prebid Cache; caching attempt was rejected. Video bid must be discarded.`); + logWarn(`Supplied video cache key was already in use by Prebid Cache; caching attempt was rejected. Video bid must be discarded.`); doCallbacksIfTimedout(auctionInstance, bidResponse); } else { @@ -688,12 +691,12 @@ export function getStandardBidderSettings(mediaType, bidderCode, bidReq) { }); // Adding hb_cache_host - if (config.getConfig('cache.url') && (!bidderCode || utils.deepAccess(bidderSettings, `${bidderCode}.sendStandardTargeting`) !== false)) { + if (config.getConfig('cache.url') && (!bidderCode || deepAccess(bidderSettings, `${bidderCode}.sendStandardTargeting`) !== false)) { const urlInfo = parseUrl(config.getConfig('cache.url')); if (typeof find(adserverTargeting, targetingKeyVal => targetingKeyVal.key === TARGETING_KEYS.CACHE_HOST) === 'undefined') { adserverTargeting.push(createKeyVal(TARGETING_KEYS.CACHE_HOST, function(bidResponse) { - return utils.deepAccess(bidResponse, `adserverTargeting.${TARGETING_KEYS.CACHE_HOST}`) + return deepAccess(bidResponse, `adserverTargeting.${TARGETING_KEYS.CACHE_HOST}`) ? bidResponse.adserverTargeting[TARGETING_KEYS.CACHE_HOST] : urlInfo.hostname; })); } @@ -735,19 +738,19 @@ function setKeys(keyValues, bidderSettings, custBidObj) { var targeting = bidderSettings[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING]; custBidObj.size = custBidObj.getSize(); - utils._each(targeting, function (kvPair) { + _each(targeting, function (kvPair) { var key = kvPair.key; var value = kvPair.val; if (keyValues[key]) { - utils.logWarn('The key: ' + key + ' is getting ovewritten'); + logWarn('The key: ' + key + ' is getting ovewritten'); } - if (utils.isFn(value)) { + if (isFn(value)) { try { value = value(custBidObj); } catch (e) { - utils.logError('bidmanager', 'ERROR', e); + logError('bidmanager', 'ERROR', e); } } @@ -755,12 +758,12 @@ function setKeys(keyValues, bidderSettings, custBidObj) { ((typeof bidderSettings.suppressEmptyKeys !== 'undefined' && bidderSettings.suppressEmptyKeys === true) || key === CONSTANTS.TARGETING_KEYS.DEAL) && // hb_deal is suppressed automatically if not set ( - utils.isEmptyStr(value) || + isEmptyStr(value) || value === null || value === undefined ) ) { - utils.logInfo("suppressing empty key '" + key + "' from adserver targeting"); + logInfo("suppressing empty key '" + key + "' from adserver targeting"); } else { keyValues[key] = value; } @@ -783,7 +786,7 @@ export function adjustBids(bid) { try { bidPriceAdjusted = bidCpmAdjustment(bid.cpm, Object.assign({}, bid)); } catch (e) { - utils.logError('Error during bid adjustment', 'bidmanager.js', e); + logError('Error during bid adjustment', 'bidmanager.js', e); } } } From f7bd90c4eb7bba8f7198bae9a7d3fe393347d21a Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 21:58:52 -0700 Subject: [PATCH 11/19] bidfactory: not importing * from utils --- src/bidfactory.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bidfactory.js b/src/bidfactory.js index 8701184c799..e15112f1735 100644 --- a/src/bidfactory.js +++ b/src/bidfactory.js @@ -1,4 +1,4 @@ -var utils = require('./utils.js'); +import { getUniqueIdentifierStr } from './utils.js'; /** Required paramaters @@ -22,7 +22,7 @@ function Bid(statusCode, bidRequest) { this.width = 0; this.height = 0; this.statusMessage = _getStatus(); - this.adId = utils.getUniqueIdentifierStr(); + this.adId = getUniqueIdentifierStr(); this.requestId = bidRequest && bidRequest.bidId; this.mediaType = 'banner'; this.source = _bidSrc; From 49f63623b5d584f09010f21bdaedafb43982ec5c Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 22:08:06 -0700 Subject: [PATCH 12/19] config: not importing * from utils --- src/config.js | 102 +++++++++++++++++++++++++------------------------- 1 file changed, 52 insertions(+), 50 deletions(-) diff --git a/src/config.js b/src/config.js index c05a1d9e2a9..72d760c5b87 100644 --- a/src/config.js +++ b/src/config.js @@ -16,13 +16,15 @@ import { isValidPriceConfig } from './cpmBucketManager.js'; import find from 'core-js-pure/features/array/find.js'; import includes from 'core-js-pure/features/array/includes.js'; import Set from 'core-js-pure/features/set'; -import { mergeDeep, deepClone } from './utils.js'; +import { + mergeDeep, deepClone, getParameterByName, isPlainObject, logMessage, logWarn, logError, + isArray, isStr, isBoolean, deepAccess, bind +} from './utils.js'; const from = require('core-js-pure/features/array/from.js'); -const utils = require('./utils.js'); const CONSTANTS = require('./constants.json'); -const DEFAULT_DEBUG = utils.getParameterByName(CONSTANTS.DEBUG_MODE).toUpperCase() === 'TRUE'; +const DEFAULT_DEBUG = getParameterByName(CONSTANTS.DEBUG_MODE).toUpperCase() === 'TRUE'; const DEFAULT_BIDDER_TIMEOUT = 3000; const DEFAULT_PUBLISHER_DOMAIN = window.location.origin; const DEFAULT_ENABLE_SEND_ALL_BIDS = true; @@ -103,10 +105,10 @@ export function newConfig() { if (validatePriceGranularity(val)) { if (typeof val === 'string') { this._priceGranularity = (hasGranularity(val)) ? val : GRANULARITY_OPTIONS.MEDIUM; - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { this._customPriceBucket = val; this._priceGranularity = GRANULARITY_OPTIONS.CUSTOM; - utils.logMessage('Using custom price granularity'); + logMessage('Using custom price granularity'); } } }, @@ -133,12 +135,12 @@ export function newConfig() { if (validatePriceGranularity(val[item])) { if (typeof val === 'string') { aggregate[item] = (hasGranularity(val[item])) ? val[item] : this._priceGranularity; - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { aggregate[item] = val[item]; - utils.logMessage(`Using custom price granularity for ${item}`); + logMessage(`Using custom price granularity for ${item}`); } } else { - utils.logWarn(`Invalid price granularity for media type: ${item}`); + logWarn(`Invalid price granularity for media type: ${item}`); } return aggregate; }, {}); @@ -180,7 +182,7 @@ export function newConfig() { if (VALID_ORDERS[val]) { this._bidderSequence = val; } else { - utils.logWarn(`Invalid order: ${val}. Bidder Sequence was not set.`); + logWarn(`Invalid order: ${val}. Bidder Sequence was not set.`); } }, @@ -242,16 +244,16 @@ export function newConfig() { function validatePriceGranularity(val) { if (!val) { - utils.logError('Prebid Error: no value passed to `setPriceGranularity()`'); + logError('Prebid Error: no value passed to `setPriceGranularity()`'); return false; } if (typeof val === 'string') { if (!hasGranularity(val)) { - utils.logWarn('Prebid Warning: setPriceGranularity was called with invalid setting, using `medium` as default.'); + logWarn('Prebid Warning: setPriceGranularity was called with invalid setting, using `medium` as default.'); } - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { if (!isValidPriceConfig(val)) { - utils.logError('Invalid custom price value passed to `setPriceGranularity()`'); + logError('Invalid custom price value passed to `setPriceGranularity()`'); return false; } } @@ -259,27 +261,27 @@ export function newConfig() { } function validateauctionOptions(val) { - if (!utils.isPlainObject(val)) { - utils.logWarn('Auction Options must be an object') + if (!isPlainObject(val)) { + logWarn('Auction Options must be an object') return false } for (let k of Object.keys(val)) { if (k !== 'secondaryBidders' && k !== 'suppressStaleRender') { - utils.logWarn(`Auction Options given an incorrect param: ${k}`) + logWarn(`Auction Options given an incorrect param: ${k}`) return false } if (k === 'secondaryBidders') { - if (!utils.isArray(val[k])) { - utils.logWarn(`Auction Options ${k} must be of type Array`); + if (!isArray(val[k])) { + logWarn(`Auction Options ${k} must be of type Array`); return false - } else if (!val[k].every(utils.isStr)) { - utils.logWarn(`Auction Options ${k} must be only string`); + } else if (!val[k].every(isStr)) { + logWarn(`Auction Options ${k} must be only string`); return false } } else if (k === 'suppressStaleRender') { - if (!utils.isBoolean(val[k])) { - utils.logWarn(`Auction Options ${k} must be of type boolean`); + if (!isBoolean(val[k])) { + logWarn(`Auction Options ${k} must be of type boolean`); return false; } } @@ -293,7 +295,7 @@ export function newConfig() { * @private */ function _getConfig() { - if (currBidder && bidderConfig && utils.isPlainObject(bidderConfig[currBidder])) { + if (currBidder && bidderConfig && isPlainObject(bidderConfig[currBidder])) { let currBidderConfig = bidderConfig[currBidder]; const configTopicSet = new Set(Object.keys(config).concat(Object.keys(currBidderConfig))); @@ -303,7 +305,7 @@ export function newConfig() { } else if (typeof config[topic] === 'undefined') { memo[topic] = currBidderConfig[topic]; } else { - if (utils.isPlainObject(currBidderConfig[topic])) { + if (isPlainObject(currBidderConfig[topic])) { memo[topic] = mergeDeep({}, config[topic], currBidderConfig[topic]); } else { memo[topic] = currBidderConfig[topic]; @@ -329,7 +331,7 @@ export function newConfig() { if (args.length <= 1 && typeof args[0] !== 'function') { const option = args[0]; const configClone = deepClone(_getConfig()); - return option ? utils.deepAccess(configClone, option) : configClone; + return option ? deepAccess(configClone, option) : configClone; } return subscribe(...args); @@ -346,7 +348,7 @@ export function newConfig() { function getConfig(...args) { if (args.length <= 1 && typeof args[0] !== 'function') { const option = args[0]; - return option ? utils.deepAccess(_getConfig(), option) : _getConfig(); + return option ? deepAccess(_getConfig(), option) : _getConfig(); } return subscribe(...args); @@ -371,9 +373,9 @@ export function newConfig() { let prop = (type === 'site') ? 'context' : type; duplicate[prop] = (prop === 'context' || prop === 'user') ? Object.keys(obj[type]).filter(key => key !== 'data').reduce((result, key) => { if (key === 'ext') { - utils.mergeDeep(result, obj[type][key]); + mergeDeep(result, obj[type][key]); } else { - utils.mergeDeep(result, {[key]: obj[type][key]}); + mergeDeep(result, {[key]: obj[type][key]}); } return result; @@ -391,14 +393,14 @@ export function newConfig() { let duplicate = {}; - if (utils.deepAccess(obj, 'ext.data')) { + if (deepAccess(obj, 'ext.data')) { Object.keys(obj.ext.data).forEach((key) => { if (key === 'pbadslot') { - utils.mergeDeep(duplicate, {context: {pbAdSlot: obj.ext.data[key]}}); + mergeDeep(duplicate, {context: {pbAdSlot: obj.ext.data[key]}}); } else if (key === 'adserver') { - utils.mergeDeep(duplicate, {context: {adServer: obj.ext.data[key]}}); + mergeDeep(duplicate, {context: {adServer: obj.ext.data[key]}}); } else { - utils.mergeDeep(duplicate, {context: {data: {[key]: obj.ext.data[key]}}}); + mergeDeep(duplicate, {context: {data: {[key]: obj.ext.data[key]}}}); } }); } @@ -416,9 +418,9 @@ export function newConfig() { let prop = (type === 'context') ? 'site' : type; duplicate[prop] = (prop === 'site' || prop === 'user') ? Object.keys(opt[type]).reduce((result, key) => { if (key === 'data') { - utils.mergeDeep(result, {ext: {data: opt[type][key]}}); + mergeDeep(result, {ext: {data: opt[type][key]}}); } else { - utils.mergeDeep(result, {[key]: opt[type][key]}); + mergeDeep(result, {[key]: opt[type][key]}); } return result; @@ -438,14 +440,14 @@ export function newConfig() { Object.keys(opt).filter(prop => prop === 'context').forEach((type) => { Object.keys(opt[type]).forEach((key) => { if (key === 'data') { - utils.mergeDeep(duplicate, {ext: {data: opt[type][key]}}); + mergeDeep(duplicate, {ext: {data: opt[type][key]}}); } else { if (typeof opt[type][key] === 'object' && !Array.isArray(opt[type][key])) { Object.keys(opt[type][key]).forEach(data => { - utils.mergeDeep(duplicate, {ext: {data: {[key.toLowerCase()]: {[data.toLowerCase()]: opt[type][key][data]}}}}); + mergeDeep(duplicate, {ext: {data: {[key.toLowerCase()]: {[data.toLowerCase()]: opt[type][key][data]}}}}); }); } else { - utils.mergeDeep(duplicate, {ext: {data: {[key.toLowerCase()]: opt[type][key]}}}); + mergeDeep(duplicate, {ext: {data: {[key.toLowerCase()]: opt[type][key]}}}); } } }); @@ -462,7 +464,7 @@ export function newConfig() { arr.forEach((adunit) => { if (adunit.fpd) { - (adunit['ortb2Imp']) ? utils.mergeDeep(adunit['ortb2Imp'], convertImpFpd(adunit.fpd)) : adunit['ortb2Imp'] = convertImpFpd(adunit.fpd); + (adunit['ortb2Imp']) ? mergeDeep(adunit['ortb2Imp'], convertImpFpd(adunit.fpd)) : adunit['ortb2Imp'] = convertImpFpd(adunit.fpd); convert.push((({ fpd, ...duplicate }) => duplicate)(adunit)); } else { convert.push(adunit); @@ -477,8 +479,8 @@ export function newConfig() { * listeners that were added by the `subscribe` function */ function setConfig(options) { - if (!utils.isPlainObject(options)) { - utils.logError('setConfig options must be an object'); + if (!isPlainObject(options)) { + logError('setConfig options must be an object'); return; } @@ -489,7 +491,7 @@ export function newConfig() { let prop = (topic === 'fpd') ? 'ortb2' : topic; let option = (topic === 'fpd') ? convertFpd(options[topic]) : options[topic]; - if (utils.isPlainObject(defaults[prop]) && utils.isPlainObject(option)) { + if (isPlainObject(defaults[prop]) && isPlainObject(option)) { option = Object.assign({}, defaults[prop], option); } @@ -504,8 +506,8 @@ export function newConfig() { * @param {object} options */ function setDefaults(options) { - if (!utils.isPlainObject(defaults)) { - utils.logError('defaults must be an object'); + if (!isPlainObject(defaults)) { + logError('defaults must be an object'); return; } @@ -546,7 +548,7 @@ export function newConfig() { } if (typeof callback !== 'function') { - utils.logError('listener must be a function'); + logError('listener must be a function'); return; } @@ -589,7 +591,7 @@ export function newConfig() { let prop = (topic === 'fpd') ? 'ortb2' : topic; let option = (topic === 'fpd') ? convertFpd(config.config[topic]) : config.config[topic]; - if (utils.isPlainObject(option)) { + if (isPlainObject(option)) { bidderConfig[bidder][prop] = Object.assign({}, bidderConfig[bidder][prop] || {}, option); } else { bidderConfig[bidder][prop] = option; @@ -597,16 +599,16 @@ export function newConfig() { }); }); } catch (e) { - utils.logError(e); + logError(e); } function check(obj) { - if (!utils.isPlainObject(obj)) { + if (!isPlainObject(obj)) { throw 'setBidderConfig bidder options must be an object'; } if (!(Array.isArray(obj.bidders) && obj.bidders.length)) { throw 'setBidderConfig bidder options must contain a bidders list with at least 1 bidder'; } - if (!utils.isPlainObject(obj.config)) { + if (!isPlainObject(obj.config)) { throw 'setBidderConfig bidder options must contain a config object'; } } @@ -627,9 +629,9 @@ export function newConfig() { return function(cb) { return function(...args) { if (typeof cb === 'function') { - return runWithBidder(bidder, utils.bind.call(cb, this, ...args)) + return runWithBidder(bidder, bind.call(cb, this, ...args)) } else { - utils.logWarn('config.callbackWithBidder callback is not a function'); + logWarn('config.callbackWithBidder callback is not a function'); } } } From 194a790265ee70d04f85c1286f531366afcd6700 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Wed, 22 Sep 2021 22:12:39 -0700 Subject: [PATCH 13/19] cpmBucketManager: not importing * from utils --- src/cpmBucketManager.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cpmBucketManager.js b/src/cpmBucketManager.js index a6b76cc38e2..b90dc8df717 100644 --- a/src/cpmBucketManager.js +++ b/src/cpmBucketManager.js @@ -1,5 +1,5 @@ import find from 'core-js-pure/features/array/find.js'; -const utils = require('./utils.js'); +import { isEmpty } from './utils.js'; const _defaultPrecision = 2; const _lgPriceConfig = { @@ -102,7 +102,7 @@ function getCpmStringValue(cpm, config, granularityMultiplier) { } function isValidPriceConfig(config) { - if (utils.isEmpty(config) || !config.buckets || !Array.isArray(config.buckets)) { + if (isEmpty(config) || !config.buckets || !Array.isArray(config.buckets)) { return false; } let isValid = true; From 9206406dfcdab61d3382abd779dd40bd95f276d7 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:18:20 -0700 Subject: [PATCH 14/19] prebid: not importing * from utils --- src/prebid.js | 166 ++++++++++++++++++++++++++------------------------ 1 file changed, 85 insertions(+), 81 deletions(-) diff --git a/src/prebid.js b/src/prebid.js index 31fb1ac410e..855d53d7de0 100644 --- a/src/prebid.js +++ b/src/prebid.js @@ -1,7 +1,12 @@ /** @module pbjs */ import { getGlobal } from './prebidGlobal.js'; -import { adUnitsFilter, flatten, getHighestCpm, isArrayOfNums, isGptPubadsDefined, uniques } from './utils.js'; +import { + adUnitsFilter, flatten, getHighestCpm, isArrayOfNums, isGptPubadsDefined, uniques, logInfo, + contains, logError, isArray, deepClone, deepAccess, isNumber, logWarn, logMessage, isFn, + transformAdServerTargetingObj, bind, replaceAuctionPrice, replaceClickThrough, insertElement, + inIframe, callBurl, createInvisibleIframe, generateUUID, unsupportedBidderMessage, isEmpty +} from './utils.js'; import { listenMessagesFromCreative } from './secureCreatives.js'; import { userSync } from './userSync.js'; import { config } from './config.js'; @@ -17,7 +22,6 @@ import { storageCallbacks } from './storageManager.js'; const $$PREBID_GLOBAL$$ = getGlobal(); const CONSTANTS = require('./constants.json'); -const utils = require('./utils.js'); const adapterManager = require('./adapterManager.js').default; const events = require('./events.js'); const { triggerUserSyncs } = userSync; @@ -41,7 +45,7 @@ $$PREBID_GLOBAL$$.libLoaded = true; // version auto generated from build $$PREBID_GLOBAL$$.version = 'v$prebid.version$'; -utils.logInfo('Prebid.js v$prebid.version$ loaded'); +logInfo('Prebid.js v$prebid.version$ loaded'); // modules list generated from build $$PREBID_GLOBAL$$.installedModules = ['v$prebid.modulesList$']; @@ -57,8 +61,8 @@ function checkDefinedPlacement(id) { .reduce(flatten) .filter(uniques); - if (!utils.contains(adUnitCodes, id)) { - utils.logError('The "' + id + '" placement is not defined.'); + if (!contains(adUnitCodes, id)) { + logError('The "' + id + '" placement is not defined.'); return; } @@ -74,7 +78,7 @@ function setRenderSize(doc, width, height) { function validateSizes(sizes, targLength) { let cleanSizes = []; - if (utils.isArray(sizes) && ((targLength) ? sizes.length === targLength : sizes.length > 0)) { + if (isArray(sizes) && ((targLength) ? sizes.length === targLength : sizes.length > 0)) { // check if an array of arrays or array of numbers if (sizes.every(sz => isArrayOfNums(sz, 2))) { cleanSizes = sizes; @@ -86,7 +90,7 @@ function validateSizes(sizes, targLength) { } function validateBannerMediaType(adUnit) { - const validatedAdUnit = utils.deepClone(adUnit); + const validatedAdUnit = deepClone(adUnit); const banner = validatedAdUnit.mediaTypes.banner; const bannerSizes = validateSizes(banner.sizes); if (bannerSizes.length > 0) { @@ -94,14 +98,14 @@ function validateBannerMediaType(adUnit) { // Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.banner.sizes validatedAdUnit.sizes = bannerSizes; } else { - utils.logError('Detected a mediaTypes.banner object without a proper sizes field. Please ensure the sizes are listed like: [[300, 250], ...]. Removing invalid mediaTypes.banner object from request.'); + logError('Detected a mediaTypes.banner object without a proper sizes field. Please ensure the sizes are listed like: [[300, 250], ...]. Removing invalid mediaTypes.banner object from request.'); delete validatedAdUnit.mediaTypes.banner } return validatedAdUnit; } function validateVideoMediaType(adUnit) { - const validatedAdUnit = utils.deepClone(adUnit); + const validatedAdUnit = deepClone(adUnit); const video = validatedAdUnit.mediaTypes.video; if (video.playerSize) { let tarPlayerSizeLen = (typeof video.playerSize[0] === 'number') ? 2 : 1; @@ -109,13 +113,13 @@ function validateVideoMediaType(adUnit) { const videoSizes = validateSizes(video.playerSize, tarPlayerSizeLen); if (videoSizes.length > 0) { if (tarPlayerSizeLen === 2) { - utils.logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.'); + logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.'); } video.playerSize = videoSizes; // Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.video.playerSize validatedAdUnit.sizes = videoSizes; } else { - utils.logError('Detected incorrect configuration of mediaTypes.video.playerSize. Please specify only one set of dimensions in a format like: [[640, 480]]. Removing invalid mediaTypes.video.playerSize property from request.'); + logError('Detected incorrect configuration of mediaTypes.video.playerSize. Please specify only one set of dimensions in a format like: [[640, 480]]. Removing invalid mediaTypes.video.playerSize property from request.'); delete validatedAdUnit.mediaTypes.video.playerSize; } } @@ -123,30 +127,30 @@ function validateVideoMediaType(adUnit) { } function validateNativeMediaType(adUnit) { - const validatedAdUnit = utils.deepClone(adUnit); + const validatedAdUnit = deepClone(adUnit); const native = validatedAdUnit.mediaTypes.native; if (native.image && native.image.sizes && !Array.isArray(native.image.sizes)) { - utils.logError('Please use an array of sizes for native.image.sizes field. Removing invalid mediaTypes.native.image.sizes property from request.'); + logError('Please use an array of sizes for native.image.sizes field. Removing invalid mediaTypes.native.image.sizes property from request.'); delete validatedAdUnit.mediaTypes.native.image.sizes; } if (native.image && native.image.aspect_ratios && !Array.isArray(native.image.aspect_ratios)) { - utils.logError('Please use an array of sizes for native.image.aspect_ratios field. Removing invalid mediaTypes.native.image.aspect_ratios property from request.'); + logError('Please use an array of sizes for native.image.aspect_ratios field. Removing invalid mediaTypes.native.image.aspect_ratios property from request.'); delete validatedAdUnit.mediaTypes.native.image.aspect_ratios; } if (native.icon && native.icon.sizes && !Array.isArray(native.icon.sizes)) { - utils.logError('Please use an array of sizes for native.icon.sizes field. Removing invalid mediaTypes.native.icon.sizes property from request.'); + logError('Please use an array of sizes for native.icon.sizes field. Removing invalid mediaTypes.native.icon.sizes property from request.'); delete validatedAdUnit.mediaTypes.native.icon.sizes; } return validatedAdUnit; } function validateAdUnitPos(adUnit, mediaType) { - let pos = utils.deepAccess(adUnit, `mediaTypes.${mediaType}.pos`); + let pos = deepAccess(adUnit, `mediaTypes.${mediaType}.pos`); - if (!pos || !utils.isNumber(pos) || !isFinite(pos)) { + if (!pos || !isNumber(pos) || !isFinite(pos)) { let warning = `Value of property 'pos' on ad unit ${adUnit.code} should be of type: Number`; - utils.logWarn(warning); + logWarn(warning); events.emit(CONSTANTS.EVENTS.AUCTION_DEBUG, {type: 'WARNING', arguments: warning}); delete adUnit.mediaTypes[mediaType].pos; } @@ -169,13 +173,13 @@ export const checkAdUnitSetup = hook('sync', function (adUnits) { const bids = adUnit.bids; let validatedBanner, validatedVideo, validatedNative; - if (!bids || !utils.isArray(bids)) { - utils.logError(`Detected adUnit.code '${adUnit.code}' did not have 'adUnit.bids' defined or 'adUnit.bids' is not an array. Removing adUnit from auction.`); + if (!bids || !isArray(bids)) { + logError(`Detected adUnit.code '${adUnit.code}' did not have 'adUnit.bids' defined or 'adUnit.bids' is not an array. Removing adUnit from auction.`); return; } if (!mediaTypes || Object.keys(mediaTypes).length === 0) { - utils.logError(`Detected adUnit.code '${adUnit.code}' did not have a 'mediaTypes' object defined. This is a required field for the auction, so this adUnit has been removed.`); + logError(`Detected adUnit.code '${adUnit.code}' did not have a 'mediaTypes' object defined. This is a required field for the auction, so this adUnit has been removed.`); return; } @@ -214,14 +218,14 @@ export const checkAdUnitSetup = hook('sync', function (adUnits) { * @return {Array} returnObj return bids array */ $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr = function (adunitCode) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr', arguments); // call to retrieve bids array if (adunitCode) { var res = $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode(adunitCode); - return utils.transformAdServerTargetingObj(res); + return transformAdServerTargetingObj(res); } else { - utils.logMessage('Need to call getAdserverTargetingForAdUnitCodeStr with adunitCode'); + logMessage('Need to call getAdserverTargetingForAdUnitCodeStr with adunitCode'); } }; @@ -239,7 +243,7 @@ $$PREBID_GLOBAL$$.getHighestUnusedBidResponseForAdUnitCode = function (adunitCod return bid.length ? bid.reduce(getHighestCpm) : {} } else { - utils.logMessage('Need to call getHighestUnusedBidResponseForAdUnitCode with adunitCode'); + logMessage('Need to call getHighestUnusedBidResponseForAdUnitCode with adunitCode'); } }; @@ -260,13 +264,13 @@ $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode = function (adUnitCode) { */ $$PREBID_GLOBAL$$.getAdserverTargeting = function (adUnitCode) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargeting', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargeting', arguments); return targeting.getAllTargeting(adUnitCode); }; function getBids(type) { const responses = auctionManager[type]() - .filter(utils.bind.call(adUnitsFilter, this, auctionManager.getAdUnitCodes())); + .filter(bind.call(adUnitsFilter, this, auctionManager.getAdUnitCodes())); // find the last auction id to get responses for most recent auction only const currentAuctionId = auctionManager.getLastAuctionId(); @@ -291,7 +295,7 @@ function getBids(type) { */ $$PREBID_GLOBAL$$.getNoBids = function () { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.getNoBids', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.getNoBids', arguments); return getBids('getNoBids'); }; @@ -314,7 +318,7 @@ $$PREBID_GLOBAL$$.getNoBidsForAdUnitCode = function (adUnitCode) { */ $$PREBID_GLOBAL$$.getBidResponses = function () { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.getBidResponses', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.getBidResponses', arguments); return getBids('getBidsReceived'); }; @@ -337,9 +341,9 @@ $$PREBID_GLOBAL$$.getBidResponsesForAdUnitCode = function (adUnitCode) { * @alias module:pbjs.setTargetingForGPTAsync */ $$PREBID_GLOBAL$$.setTargetingForGPTAsync = function (adUnit, customSlotMatching) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForGPTAsync', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForGPTAsync', arguments); if (!isGptPubadsDefined()) { - utils.logError('window.googletag is not defined on the page'); + logError('window.googletag is not defined on the page'); return; } @@ -370,9 +374,9 @@ $$PREBID_GLOBAL$$.setTargetingForGPTAsync = function (adUnit, customSlotMatching * @alias module:pbjs.setTargetingForAst */ $$PREBID_GLOBAL$$.setTargetingForAst = function (adUnitCodes) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForAn', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForAn', arguments); if (!targeting.isApntagDefined()) { - utils.logError('window.apntag is not defined on the page'); + logError('window.apntag is not defined on the page'); return; } @@ -387,7 +391,7 @@ function emitAdRenderFail({ reason, message, bid, id }) { if (bid) data.bid = bid; if (id) data.adId = id; - utils.logError(message); + logError(message); events.emit(AD_RENDER_FAILED, data); } @@ -407,8 +411,8 @@ function emitAdRenderSucceeded({ doc, bid, id }) { * @alias module:pbjs.renderAd */ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.renderAd', arguments); - utils.logMessage('Calling renderAd with adId :' + id); + logInfo('Invoking $$PREBID_GLOBAL$$.renderAd', arguments); + logMessage('Calling renderAd with adId :' + id); if (doc && id) { try { @@ -418,23 +422,23 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { if (bid) { let shouldRender = true; if (bid && bid.status === CONSTANTS.BID_STATUS.RENDERED) { - utils.logWarn(`Ad id ${bid.adId} has been rendered before`); + logWarn(`Ad id ${bid.adId} has been rendered before`); events.emit(STALE_RENDER, bid); - if (utils.deepAccess(config.getConfig('auctionOptions'), 'suppressStaleRender')) { + if (deepAccess(config.getConfig('auctionOptions'), 'suppressStaleRender')) { shouldRender = false; } } if (shouldRender) { // replace macros according to openRTB with price paid = bid.cpm - bid.ad = utils.replaceAuctionPrice(bid.ad, bid.cpm); - bid.adUrl = utils.replaceAuctionPrice(bid.adUrl, bid.cpm); + bid.ad = replaceAuctionPrice(bid.ad, bid.cpm); + bid.adUrl = replaceAuctionPrice(bid.adUrl, bid.cpm); // replacing clickthrough if submitted if (options && options.clickThrough) { const {clickThrough} = options; - bid.ad = utils.replaceClickThrough(bid.ad, clickThrough); - bid.adUrl = utils.replaceClickThrough(bid.adUrl, clickThrough); + bid.ad = replaceClickThrough(bid.ad, clickThrough); + bid.adUrl = replaceClickThrough(bid.adUrl, clickThrough); } // save winning bids @@ -449,9 +453,9 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { if (isRendererRequired(renderer)) { executeRenderer(renderer, bid); - utils.insertElement(creativeComment, doc, 'html'); + insertElement(creativeComment, doc, 'html'); emitAdRenderSucceeded({ doc, bid, id }); - } else if ((doc === document && !utils.inIframe()) || mediaType === 'video') { + } else if ((doc === document && !inIframe()) || mediaType === 'video') { const message = `Error trying to write ad. Ad render call ad id ${id} was prevented from writing to the main document.`; emitAdRenderFail({reason: PREVENT_WRITING_ON_MAIN_DOCUMENT, message, bid, id}); } else if (ad) { @@ -468,21 +472,21 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { doc.write(ad); doc.close(); setRenderSize(doc, width, height); - utils.insertElement(creativeComment, doc, 'html'); - utils.callBurl(bid); + insertElement(creativeComment, doc, 'html'); + callBurl(bid); emitAdRenderSucceeded({ doc, bid, id }); } else if (adUrl) { - const iframe = utils.createInvisibleIframe(); + const iframe = createInvisibleIframe(); iframe.height = height; iframe.width = width; iframe.style.display = 'inline'; iframe.style.overflow = 'hidden'; iframe.src = adUrl; - utils.insertElement(iframe, doc, 'body'); + insertElement(iframe, doc, 'body'); setRenderSize(doc, width, height); - utils.insertElement(creativeComment, doc, 'html'); - utils.callBurl(bid); + insertElement(creativeComment, doc, 'html'); + callBurl(bid); emitAdRenderSucceeded({ doc, bid, id }); } else { const message = `Error trying to write ad. No ad for bid response id: ${id}`; @@ -509,7 +513,7 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { * @alias module:pbjs.removeAdUnit */ $$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.removeAdUnit', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.removeAdUnit', arguments); if (!adUnitCode) { $$PREBID_GLOBAL$$.adUnits = []; @@ -518,7 +522,7 @@ $$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { let adUnitCodes; - if (utils.isArray(adUnitCode)) { + if (isArray(adUnitCode)) { adUnitCodes = adUnitCode; } else { adUnitCodes = [adUnitCode]; @@ -546,9 +550,9 @@ $$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { $$PREBID_GLOBAL$$.requestBids = hook('async', function ({ bidsBackHandler, timeout, adUnits, adUnitCodes, labels, auctionId } = {}) { events.emit(REQUEST_BIDS); const cbTimeout = timeout || config.getConfig('bidderTimeout'); - adUnits = (adUnits && config.convertAdUnitFpd(utils.isArray(adUnits) ? adUnits : [adUnits])) || $$PREBID_GLOBAL$$.adUnits; + adUnits = (adUnits && config.convertAdUnitFpd(isArray(adUnits) ? adUnits : [adUnits])) || $$PREBID_GLOBAL$$.adUnits; - utils.logInfo('Invoking $$PREBID_GLOBAL$$.requestBids', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.requestBids', arguments); let _s2sConfigs = []; const s2sBidders = []; @@ -588,7 +592,7 @@ $$PREBID_GLOBAL$$.requestBids = hook('async', function ({ bidsBackHandler, timeo const bidders = (s2sBidders) ? allBidders.filter(bidder => !includes(s2sBidders, bidder)) : allBidders; - adUnit.transactionId = utils.generateUUID(); + adUnit.transactionId = generateUUID(); bidders.forEach(bidder => { const adapter = bidderRegistry[bidder]; @@ -600,7 +604,7 @@ $$PREBID_GLOBAL$$.requestBids = hook('async', function ({ bidsBackHandler, timeo const bidderEligible = adUnitMediaTypes.some(type => includes(bidderMediaTypes, type)); if (!bidderEligible) { // drop the bidder from the ad unit if it's not compatible - utils.logWarn(utils.unsupportedBidderMessage(adUnit, bidder)); + logWarn(unsupportedBidderMessage(adUnit, bidder)); adUnit.bids = adUnit.bids.filter(bid => bid.bidder !== bidder); } else { adunitCounter.incrementBidderRequestsCounter(adUnit.code, bidder); @@ -610,13 +614,13 @@ $$PREBID_GLOBAL$$.requestBids = hook('async', function ({ bidsBackHandler, timeo }); if (!adUnits || adUnits.length === 0) { - utils.logMessage('No adUnits configured. No bids requested.'); + logMessage('No adUnits configured. No bids requested.'); if (typeof bidsBackHandler === 'function') { // executeCallback, this will only be called in case of first request try { bidsBackHandler(); } catch (e) { - utils.logError('Error executing bidsBackHandler', null, e); + logError('Error executing bidsBackHandler', null, e); } } return; @@ -626,7 +630,7 @@ $$PREBID_GLOBAL$$.requestBids = hook('async', function ({ bidsBackHandler, timeo let adUnitsLen = adUnits.length; if (adUnitsLen > 15) { - utils.logInfo(`Current auction ${auction.getAuctionId()} contains ${adUnitsLen} adUnits.`, adUnits); + logInfo(`Current auction ${auction.getAuctionId()} contains ${adUnitsLen} adUnits.`, adUnits); } adUnitCodes.forEach(code => targeting.setLatestAuctionForAdUnit(code, auction.getAuctionId())); @@ -656,8 +660,8 @@ $$PREBID_GLOBAL$$.requestBids.before(executeCallbacks, 49); * @alias module:pbjs.addAdUnits */ $$PREBID_GLOBAL$$.addAdUnits = function (adUnitArr) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.addAdUnits', arguments); - $$PREBID_GLOBAL$$.adUnits.push.apply($$PREBID_GLOBAL$$.adUnits, config.convertAdUnitFpd(utils.isArray(adUnitArr) ? adUnitArr : [adUnitArr])); + logInfo('Invoking $$PREBID_GLOBAL$$.addAdUnits', arguments); + $$PREBID_GLOBAL$$.adUnits.push.apply($$PREBID_GLOBAL$$.adUnits, config.convertAdUnitFpd(isArray(adUnitArr) ? adUnitArr : [adUnitArr])); // emit event events.emit(ADD_AD_UNITS); }; @@ -679,14 +683,14 @@ $$PREBID_GLOBAL$$.addAdUnits = function (adUnitArr) { * Currently `bidWon` is the only event that accepts an `id` parameter. */ $$PREBID_GLOBAL$$.onEvent = function (event, handler, id) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.onEvent', arguments); - if (!utils.isFn(handler)) { - utils.logError('The event handler provided is not a function and was not set on event "' + event + '".'); + logInfo('Invoking $$PREBID_GLOBAL$$.onEvent', arguments); + if (!isFn(handler)) { + logError('The event handler provided is not a function and was not set on event "' + event + '".'); return; } if (id && !eventValidators[event].call(null, id)) { - utils.logError('The id provided is not valid for event "' + event + '" and no handler was set.'); + logError('The id provided is not valid for event "' + event + '" and no handler was set.'); return; } @@ -700,7 +704,7 @@ $$PREBID_GLOBAL$$.onEvent = function (event, handler, id) { * @alias module:pbjs.offEvent */ $$PREBID_GLOBAL$$.offEvent = function (event, handler, id) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.offEvent', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.offEvent', arguments); if (id && !eventValidators[event].call(null, id)) { return; } @@ -714,7 +718,7 @@ $$PREBID_GLOBAL$$.offEvent = function (event, handler, id) { * @alias module:pbjs.getEvents */ $$PREBID_GLOBAL$$.getEvents = function () { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.getEvents'); + logInfo('Invoking $$PREBID_GLOBAL$$.getEvents'); return events.getEvents(); }; @@ -725,11 +729,11 @@ $$PREBID_GLOBAL$$.getEvents = function () { * @alias module:pbjs.registerBidAdapter */ $$PREBID_GLOBAL$$.registerBidAdapter = function (bidderAdaptor, bidderCode) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.registerBidAdapter', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.registerBidAdapter', arguments); try { adapterManager.registerBidAdapter(bidderAdaptor(), bidderCode); } catch (e) { - utils.logError('Error registering bidder adapter : ' + e.message); + logError('Error registering bidder adapter : ' + e.message); } }; @@ -739,11 +743,11 @@ $$PREBID_GLOBAL$$.registerBidAdapter = function (bidderAdaptor, bidderCode) { * @alias module:pbjs.registerAnalyticsAdapter */ $$PREBID_GLOBAL$$.registerAnalyticsAdapter = function (options) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.registerAnalyticsAdapter', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.registerAnalyticsAdapter', arguments); try { adapterManager.registerAnalyticsAdapter(options); } catch (e) { - utils.logError('Error registering analytics adapter : ' + e.message); + logError('Error registering analytics adapter : ' + e.message); } }; @@ -754,7 +758,7 @@ $$PREBID_GLOBAL$$.registerAnalyticsAdapter = function (options) { * @return {Object} bidResponse [description] */ $$PREBID_GLOBAL$$.createBid = function (statusCode) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.createBid', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.createBid', arguments); return createBid(statusCode); }; @@ -777,11 +781,11 @@ $$PREBID_GLOBAL$$.createBid = function (statusCode) { const enableAnalyticsCallbacks = []; const enableAnalyticsCb = hook('async', function (config) { - if (config && !utils.isEmpty(config)) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.enableAnalytics for: ', config); + if (config && !isEmpty(config)) { + logInfo('Invoking $$PREBID_GLOBAL$$.enableAnalytics for: ', config); adapterManager.enableAnalytics(config); } else { - utils.logError('$$PREBID_GLOBAL$$.enableAnalytics should be called with option {}'); + logError('$$PREBID_GLOBAL$$.enableAnalytics should be called with option {}'); } }, 'enableAnalyticsCb'); @@ -793,11 +797,11 @@ $$PREBID_GLOBAL$$.enableAnalytics = function (config) { * @alias module:pbjs.aliasBidder */ $$PREBID_GLOBAL$$.aliasBidder = function (bidderCode, alias, options) { - utils.logInfo('Invoking $$PREBID_GLOBAL$$.aliasBidder', arguments); + logInfo('Invoking $$PREBID_GLOBAL$$.aliasBidder', arguments); if (bidderCode && alias) { adapterManager.aliasBidAdapter(bidderCode, alias, options); } else { - utils.logError('bidderCode and alias must be passed as arguments', '$$PREBID_GLOBAL$$.aliasBidder'); + logError('bidderCode and alias must be passed as arguments', '$$PREBID_GLOBAL$$.aliasBidder'); } }; @@ -883,7 +887,7 @@ $$PREBID_GLOBAL$$.markWinningBidAsUsed = function (markBidRequest) { } else if (markBidRequest.adId) { bids = auctionManager.getBidsReceived().filter(bid => bid.adId === markBidRequest.adId); } else { - utils.logWarn('Improper use of markWinningBidAsUsed. It needs an adUnitCode or an adId to function.'); + logWarn('Improper use of markWinningBidAsUsed. It needs an adUnitCode or an adId to function.'); } if (bids.length > 0) { @@ -975,10 +979,10 @@ $$PREBID_GLOBAL$$.cmd.push = function (command) { try { command.call(); } catch (e) { - utils.logError('Error processing command :', e.message, e.stack); + logError('Error processing command :', e.message, e.stack); } } else { - utils.logError('Commands written into $$PREBID_GLOBAL$$.cmd.push must be wrapped in a function'); + logError('Commands written into $$PREBID_GLOBAL$$.cmd.push must be wrapped in a function'); } }; @@ -991,7 +995,7 @@ function processQueue(queue) { cmd.call(); cmd.called = true; } catch (e) { - utils.logError('Error processing command :', 'prebid.js', e); + logError('Error processing command :', 'prebid.js', e); } } }); From bc644ec4aab6d08ba62128d8d71701aebbce918d Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:22:38 -0700 Subject: [PATCH 15/19] Renderer: not importing * from utils --- src/Renderer.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Renderer.js b/src/Renderer.js index c997658b30b..1d7506418bb 100644 --- a/src/Renderer.js +++ b/src/Renderer.js @@ -1,5 +1,7 @@ import { loadExternalScript } from './adloader.js'; -import * as utils from './utils.js'; +import { + logError, logWarn, logMessage, deepAccess +} from './utils.js'; import find from 'core-js-pure/features/array/find.js'; const moduleCode = 'outstream'; @@ -25,7 +27,7 @@ export function Renderer(options) { this.cmd = []; this.push = func => { if (typeof func !== 'function') { - utils.logError('Commands given to Renderer.push must be wrapped in a function'); + logError('Commands given to Renderer.push must be wrapped in a function'); return; } this.loaded ? func.call() : this.cmd.push(func); @@ -44,7 +46,7 @@ export function Renderer(options) { if (this._render) { this._render.apply(this, renderArgs) } else { - utils.logWarn(`No render function was provided, please use .setRender on the renderer`); + logWarn(`No render function was provided, please use .setRender on the renderer`); } } @@ -53,7 +55,7 @@ export function Renderer(options) { this.cmd.unshift(runRender) // should render run first ? loadExternalScript(url, moduleCode, this.callback); } else { - utils.logWarn(`External Js not loaded by Renderer since renderer url and callback is already defined on adUnit ${adUnitCode}`); + logWarn(`External Js not loaded by Renderer since renderer url and callback is already defined on adUnit ${adUnitCode}`); runRender() } }.bind(this) // bind the function to this object to avoid 'this' errors @@ -80,7 +82,7 @@ Renderer.prototype.handleVideoEvent = function({ id, eventName }) { this.handlers[eventName](); } - utils.logMessage(`Prebid Renderer event for id ${id} type ${eventName}`); + logMessage(`Prebid Renderer event for id ${id} type ${eventName}`); }; /* @@ -92,7 +94,7 @@ Renderer.prototype.process = function() { try { this.cmd.shift().call(); } catch (error) { - utils.logError('Error processing Renderer command: ', error); + logError('Error processing Renderer command: ', error); } } }; @@ -126,11 +128,11 @@ function isRendererPreferredFromAdUnit(adUnitCode) { } // renderer defined at adUnit level - const adUnitRenderer = utils.deepAccess(adUnit, 'renderer'); + const adUnitRenderer = deepAccess(adUnit, 'renderer'); const hasValidAdUnitRenderer = !!(adUnitRenderer && adUnitRenderer.url && adUnitRenderer.render); // renderer defined at adUnit.mediaTypes level - const mediaTypeRenderer = utils.deepAccess(adUnit, 'mediaTypes.video.renderer'); + const mediaTypeRenderer = deepAccess(adUnit, 'mediaTypes.video.renderer'); const hasValidMediaTypeRenderer = !!(mediaTypeRenderer && mediaTypeRenderer.url && mediaTypeRenderer.render) return !!( From 359894c0a092e0bc15602bd8733448022c98607b Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:27:52 -0700 Subject: [PATCH 16/19] storageManager: not importing * from utils --- src/storageManager.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/storageManager.js b/src/storageManager.js index 66a0cf68cbf..888cdf24325 100644 --- a/src/storageManager.js +++ b/src/storageManager.js @@ -1,5 +1,5 @@ import {hook} from './hook.js'; -import * as utils from './utils.js'; +import { hasDeviceAccess, checkCookieSupport, logError } from './utils.js'; import includes from 'core-js-pure/features/array/includes.js'; const moduleTypeWhiteList = ['core', 'prebid-module']; @@ -40,7 +40,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) { } else { let result = { hasEnforcementHook: false, - valid: utils.hasDeviceAccess() + valid: hasDeviceAccess() } value = cb(result); } @@ -135,7 +135,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) { const cookiesAreEnabled = function (done) { let cb = function (result) { if (result && result.valid) { - if (utils.checkCookieSupport()) { + if (checkCookieSupport()) { return true; } window.document.cookie = 'prebid.cookieTest'; @@ -222,7 +222,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) { try { return !!window.localStorage; } catch (e) { - utils.logError('Local storage api disabled'); + logError('Local storage api disabled'); } } return false; @@ -247,7 +247,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) { let cb = function (result) { if (result && result.valid) { const all = []; - if (utils.hasDeviceAccess()) { + if (hasDeviceAccess()) { const cookies = document.cookie.split(';'); while (cookies.length) { const cookie = cookies.pop(); From 616f514da666a22070327b472dcf2ce7d47e9691 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:33:50 -0700 Subject: [PATCH 17/19] targeting: not importing * from utils --- src/targeting.js | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/targeting.js b/src/targeting.js index 96692376d82..7a48f26136b 100644 --- a/src/targeting.js +++ b/src/targeting.js @@ -1,4 +1,7 @@ -import { uniques, isGptPubadsDefined, getHighestCpm, getOldestHighestCpmBid, groupBy, isAdUnitCodeMatchingSlot, timestamp, deepAccess, deepClone, logError, logWarn, logInfo } from './utils.js'; +import { + uniques, isGptPubadsDefined, getHighestCpm, getOldestHighestCpmBid, groupBy, isAdUnitCodeMatchingSlot, timestamp, + deepAccess, deepClone, logError, logWarn, logInfo, isFn, isArray, logMessage, isStr +} from './utils.js'; import { config } from './config.js'; import { NATIVE_TARGETING_KEYS } from './native.js'; import { auctionManager } from './auctionManager.js'; @@ -8,7 +11,6 @@ import { hook } from './hook.js'; import includes from 'core-js-pure/features/array/includes.js'; import find from 'core-js-pure/features/array/find.js'; -const utils = require('./utils.js'); var CONSTANTS = require('./constants.json'); var pbTargetingKeys = []; @@ -122,13 +124,13 @@ export function newTargeting(auctionManager) { const adUnitCodes = getAdUnitCodes(adUnitCode); const adUnits = auctionManager.getAdUnits().filter(adUnit => includes(adUnitCodes, adUnit.code)); window.googletag.pubads().getSlots().forEach(slot => { - let customSlotMatchingFunc = utils.isFn(customSlotMatching) && customSlotMatching(slot); + let customSlotMatchingFunc = isFn(customSlotMatching) && customSlotMatching(slot); pbTargetingKeys.forEach(function(key) { // reset only registered adunits adUnits.forEach(function(unit) { if (unit.code === slot.getAdUnitPath() || unit.code === slot.getSlotElementId() || - (utils.isFn(customSlotMatchingFunc) && customSlotMatchingFunc(unit.code))) { + (isFn(customSlotMatchingFunc) && customSlotMatchingFunc(unit.code))) { slot.setTargeting(key, null); } }); @@ -160,7 +162,7 @@ export function newTargeting(auctionManager) { */ function bidShouldBeAddedToTargeting(bid, adUnitCodes) { return bid.adserverTargeting && adUnitCodes && - ((utils.isArray(adUnitCodes) && includes(adUnitCodes, bid.adUnitCode)) || + ((isArray(adUnitCodes) && includes(adUnitCodes, bid.adUnitCode)) || (typeof adUnitCodes === 'string' && bid.adUnitCode === adUnitCodes)); }; @@ -387,7 +389,7 @@ export function newTargeting(auctionManager) { } valueArr = (valueArr.length > 1) ? [valueArr] : valueArr; valueArr.map((value) => { - utils.logMessage(`Attempting to set key value for slot: ${slot.getSlotElementId()} key: ${key} value: ${value}`); + logMessage(`Attempting to set key value for slot: ${slot.getSlotElementId()} key: ${key} value: ${value}`); return value; }).forEach(value => { slot.setTargeting(key, value); @@ -405,7 +407,7 @@ export function newTargeting(auctionManager) { function getAdUnitCodes(adUnitCode) { if (typeof adUnitCode === 'string') { return [adUnitCode]; - } else if (utils.isArray(adUnitCode)) { + } else if (isArray(adUnitCode)) { return adUnitCode; } return auctionManager.getAdUnitCodes() || []; @@ -455,14 +457,14 @@ export function newTargeting(auctionManager) { try { targeting.resetPresetTargetingAST(adUnitCodes); } catch (e) { - utils.logError('unable to reset targeting for AST' + e) + logError('unable to reset targeting for AST' + e) } Object.keys(astTargeting).forEach(targetId => Object.keys(astTargeting[targetId]).forEach(key => { - utils.logMessage(`Attempting to set targeting for targetId: ${targetId} key: ${key} value: ${astTargeting[targetId][key]}`); + logMessage(`Attempting to set targeting for targetId: ${targetId} key: ${key} value: ${astTargeting[targetId][key]}`); // setKeywords supports string and array as value - if (utils.isStr(astTargeting[targetId][key]) || utils.isArray(astTargeting[targetId][key])) { + if (isStr(astTargeting[targetId][key]) || isArray(astTargeting[targetId][key])) { let keywordsObj = {}; let regex = /pt[0-9]/; if (key.search(regex) < 0) { @@ -527,7 +529,7 @@ export function newTargeting(auctionManager) { function mergeAdServerTargeting(acc, bid, index, arr) { function concatTargetingValue(key) { return function(currentBidElement) { - if (!utils.isArray(currentBidElement.adserverTargeting[key])) { + if (!isArray(currentBidElement.adserverTargeting[key])) { currentBidElement.adserverTargeting[key] = [currentBidElement.adserverTargeting[key]]; } currentBidElement.adserverTargeting[key] = currentBidElement.adserverTargeting[key].concat(bid.adserverTargeting[key]).filter(uniques); @@ -634,8 +636,8 @@ export function newTargeting(auctionManager) { return Object.keys(aut) .map(function(key) { - if (utils.isStr(aut[key])) aut[key] = aut[key].split(',').map(s => s.trim()); - if (!utils.isArray(aut[key])) aut[key] = [ aut[key] ]; + if (isStr(aut[key])) aut[key] = aut[key].split(',').map(s => s.trim()); + if (!isArray(aut[key])) aut[key] = [ aut[key] ]; return { [key]: aut[key] }; }); } @@ -648,7 +650,7 @@ export function newTargeting(auctionManager) { } targeting.isApntagDefined = function() { - if (window.apntag && utils.isFn(window.apntag.setKeywords)) { + if (window.apntag && isFn(window.apntag.setKeywords)) { return true; } }; From e82d06cd973d3bf36f5ecc2d92c48d24d9d80c9f Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:42:27 -0700 Subject: [PATCH 18/19] userSync: not importing * from utils --- src/userSync.js | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/userSync.js b/src/userSync.js index f653880fa29..30dac71e5b8 100644 --- a/src/userSync.js +++ b/src/userSync.js @@ -1,4 +1,7 @@ -import * as utils from './utils.js'; +import { + deepClone, isPlainObject, logError, shuffle, logMessage, triggerPixel, insertUserSyncIframe, isArray, + logWarn, isStr, isSafariBrowser +} from './utils.js'; import { config } from './config.js'; import includes from 'core-js-pure/features/array/includes.js'; import { getCoreStorageManager } from './storageManager.js'; @@ -18,7 +21,7 @@ export const USERSYNC_DEFAULT_CONFIG = { // Set userSync default values config.setDefaults({ - 'userSync': utils.deepClone(USERSYNC_DEFAULT_CONFIG) + 'userSync': deepClone(USERSYNC_DEFAULT_CONFIG) }); const storage = getCoreStorageManager('usersync'); @@ -54,7 +57,7 @@ export function newUserSync(userSyncDependencies) { // if userSync.filterSettings does not contain image/all configs, merge in default image config to ensure image pixels are fired if (conf.userSync) { let fs = conf.userSync.filterSettings; - if (utils.isPlainObject(fs)) { + if (isPlainObject(fs)) { if (!fs.image && !fs.all) { conf.userSync.filterSettings.image = { bidders: '*', @@ -96,7 +99,7 @@ export function newUserSync(userSyncDependencies) { // Iframe syncs loadIframes(); } catch (e) { - return utils.logError('Error firing user syncs', e); + return logError('Error firing user syncs', e); } // Reset the user sync queue queue = getDefaultQueue(); @@ -106,7 +109,7 @@ export function newUserSync(userSyncDependencies) { // Randomize the order of the pixels before firing // This is to avoid giving any bidder who has registered multiple syncs // any preferential treatment and balancing them out - utils.shuffle(queue).forEach((sync) => { + shuffle(queue).forEach((sync) => { fn(sync); hasFiredBidder.add(sync[0]); }); @@ -123,9 +126,9 @@ export function newUserSync(userSyncDependencies) { } forEachFire(queue.image, (sync) => { let [bidderName, trackingPixelUrl] = sync; - utils.logMessage(`Invoking image pixel user sync for bidder: ${bidderName}`); + logMessage(`Invoking image pixel user sync for bidder: ${bidderName}`); // Create image object and add the src url - utils.triggerPixel(trackingPixelUrl); + triggerPixel(trackingPixelUrl); }); } @@ -140,9 +143,9 @@ export function newUserSync(userSyncDependencies) { } forEachFire(queue.iframe, (sync) => { let [bidderName, iframeUrl] = sync; - utils.logMessage(`Invoking iframe user sync for bidder: ${bidderName}`); + logMessage(`Invoking iframe user sync for bidder: ${bidderName}`); // Insert iframe into DOM - utils.insertUserSyncIframe(iframeUrl); + insertUserSyncIframe(iframeUrl); }); } @@ -177,21 +180,21 @@ export function newUserSync(userSyncDependencies) { */ publicApi.registerSync = (type, bidder, url) => { if (hasFiredBidder.has(bidder)) { - return utils.logMessage(`already fired syncs for "${bidder}", ignoring registerSync call`); + return logMessage(`already fired syncs for "${bidder}", ignoring registerSync call`); } - if (!usConfig.syncEnabled || !utils.isArray(queue[type])) { - return utils.logWarn(`User sync type "${type}" not supported`); + if (!usConfig.syncEnabled || !isArray(queue[type])) { + return logWarn(`User sync type "${type}" not supported`); } if (!bidder) { - return utils.logWarn(`Bidder is required for registering sync`); + return logWarn(`Bidder is required for registering sync`); } if (usConfig.syncsPerBidder !== 0 && Number(numAdapterBids[bidder]) >= usConfig.syncsPerBidder) { - return utils.logWarn(`Number of user syncs exceeded for "${bidder}"`); + return logWarn(`Number of user syncs exceeded for "${bidder}"`); } const canBidderRegisterSync = publicApi.canBidderRegisterSync(type, bidder); if (!canBidderRegisterSync) { - return utils.logWarn(`Bidder "${bidder}" not permitted to register their "${type}" userSync pixels.`); + return logWarn(`Bidder "${bidder}" not permitted to register their "${type}" userSync pixels.`); } // the bidder's pixel has passed all checks and is allowed to register @@ -238,7 +241,7 @@ export function newUserSync(userSyncDependencies) { */ function isFilterConfigValid(filterConfig, type) { if (filterConfig.all && filterConfig[type]) { - utils.logWarn(`Detected presence of the "filterSettings.all" and "filterSettings.${type}" in userSync config. You cannot mix "all" with "iframe/image" configs; they are mutually exclusive.`); + logWarn(`Detected presence of the "filterSettings.all" and "filterSettings.${type}" in userSync config. You cannot mix "all" with "iframe/image" configs; they are mutually exclusive.`); return false; } @@ -255,12 +258,12 @@ export function newUserSync(userSyncDependencies) { let biddersField = activeConfig.bidders; if (filterField && filterField !== 'include' && filterField !== 'exclude') { - utils.logWarn(`UserSync "filterSettings.${activeConfigName}.filter" setting '${filterField}' is not a valid option; use either 'include' or 'exclude'.`); + logWarn(`UserSync "filterSettings.${activeConfigName}.filter" setting '${filterField}' is not a valid option; use either 'include' or 'exclude'.`); return false; } - if (biddersField !== '*' && !(Array.isArray(biddersField) && biddersField.length > 0 && biddersField.every(bidderInList => utils.isStr(bidderInList) && bidderInList !== '*'))) { - utils.logWarn(`Detected an invalid setup in userSync "filterSettings.${activeConfigName}.bidders"; use either '*' (to represent all bidders) or an array of bidders.`); + if (biddersField !== '*' && !(Array.isArray(biddersField) && biddersField.length > 0 && biddersField.every(bidderInList => isStr(bidderInList) && bidderInList !== '*'))) { + logWarn(`Detected an invalid setup in userSync "filterSettings.${activeConfigName}.bidders"; use either '*' (to represent all bidders) or an array of bidders.`); return false; } @@ -302,7 +305,7 @@ export function newUserSync(userSyncDependencies) { return publicApi; } -const browserSupportsCookies = !utils.isSafariBrowser() && storage.cookiesAreEnabled(); +const browserSupportsCookies = !isSafariBrowser() && storage.cookiesAreEnabled(); export const userSync = newUserSync({ config: config.getConfig('userSync'), From 183f383f629baab34e1d6f883dfe93d1cc2f8519 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Thu, 23 Sep 2021 11:47:36 -0700 Subject: [PATCH 19/19] videoCache: not importing * from utils --- src/videoCache.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/videoCache.js b/src/videoCache.js index 9e378d90574..57618024c32 100644 --- a/src/videoCache.js +++ b/src/videoCache.js @@ -11,7 +11,7 @@ import { ajax } from './ajax.js'; import { config } from './config.js'; -import * as utils from './utils.js'; +import { isPlainObject } from './utils.js'; /** * @typedef {object} CacheableUrlBid @@ -73,7 +73,7 @@ function toStorageRequest(bid) { payload.bidid = bid.requestId; payload.aid = bid.auctionId; // function has a thisArg set to bidderRequest for accessing the auctionStart - if (utils.isPlainObject(this) && this.hasOwnProperty('auctionStart')) { + if (isPlainObject(this) && this.hasOwnProperty('auctionStart')) { payload.timestamp = this.auctionStart; } }