From 6b8c5941042aeb646ee14e574ac88630be7023df Mon Sep 17 00:00:00 2001 From: Tiago Peczenyj Date: Wed, 22 Sep 2021 15:46:29 +0200 Subject: [PATCH 01/84] Weborama Real-time Data Module: add new RTD module (#7437) * add first version * small fixes * fix email * fix token encoding * update doc * add unit test, fix small code issues * add option about ortb2 * update doc * format doc * fix example * update example * rename module name to weborama * add placement id * keep ortb2 feature not active by default * remove gam key renaming options * fix typo in doc * fix typo * fix typo 2 Co-authored-by: Tiago Peczenyj --- .../gpt/weboramaRtdProvider_example.html | 126 ++++++++ modules/weboramaRtdProvider.js | 174 +++++++++++ modules/weboramaRtdProvider.md | 70 +++++ test/spec/modules/weboramaRtdProvider_spec.js | 288 ++++++++++++++++++ 4 files changed, 658 insertions(+) create mode 100644 integrationExamples/gpt/weboramaRtdProvider_example.html create mode 100644 modules/weboramaRtdProvider.js create mode 100644 modules/weboramaRtdProvider.md create mode 100644 test/spec/modules/weboramaRtdProvider_spec.js diff --git a/integrationExamples/gpt/weboramaRtdProvider_example.html b/integrationExamples/gpt/weboramaRtdProvider_example.html new file mode 100644 index 00000000000..824d7a2f0c7 --- /dev/null +++ b/integrationExamples/gpt/weboramaRtdProvider_example.html @@ -0,0 +1,126 @@ + + + + + + + + + + + + + +
+

+test webo ctx using prebid.js +

+
+

Basic Prebid.js Example

+
Div-1
+
+ +
+ + + diff --git a/modules/weboramaRtdProvider.js b/modules/weboramaRtdProvider.js new file mode 100644 index 00000000000..141b88a48da --- /dev/null +++ b/modules/weboramaRtdProvider.js @@ -0,0 +1,174 @@ +/** + * This module adds Weborama provider to the real time data module + * The {@link module:modules/realTimeData} module is required + * The module will fetch contextual data (page-centric) from Weborama server + * @module modules/weboramaRtdProvider + * @requires module:modules/realTimeData + */ + +/** +* @typedef {Object} ModuleParams +* @property {WeboCtxConf} weboCtxConf +*/ + +/** +* @typedef {Object} WeboCtxConf +* @property {string} token required token to be used on bigsea contextual API requests +* @property {?string} targetURL specify the target url instead use the referer +* @property {?boolean} setTargeting if true will set the GAM targeting +* @property {?object} defaultProfile to be used if the profile is not found +*/ + +import * as utils from '../src/utils.js'; +import {submodule} from '../src/hook.js'; +import {ajax} from '../src/ajax.js'; +import {config} from '../src/config.js'; + +/** @type {string} */ +const MODULE_NAME = 'realTimeData'; +/** @type {string} */ +const SUBMODULE_NAME = 'weborama'; +/** @type {string} */ +const WEBO_CTX = 'webo_ctx'; +/** @type {string} */ +const WEBO_DS = 'webo_ds'; + +/** @type {null|Object} */ +let _bigseaContextualProfile = null; + +/** function that provides ad server targeting data to RTD-core +* @param {Array} adUnitsCodes +* @param {Object} moduleConfig +* @returns {Object} target data + */ +function getTargetingData(adUnitsCodes, moduleConfig) { + moduleConfig = moduleConfig || {}; + const moduleParams = moduleConfig.params || {}; + const weboCtxConf = moduleParams.weboCtxConf || {}; + const defaultContextualProfiles = weboCtxConf.defaultProfile || {} + const profile = _bigseaContextualProfile || defaultContextualProfiles; + + if (weboCtxConf.setOrtb2) { + const ortb2 = config.getConfig('ortb2') || {}; + if (profile[WEBO_CTX]) { + utils.deepSetValue(ortb2, 'site.ext.data.webo_ctx', profile[WEBO_CTX]); + } + if (profile[WEBO_DS]) { + utils.deepSetValue(ortb2, 'site.ext.data.webo_ds', profile[WEBO_DS]); + } + config.setConfig({ortb2: ortb2}); + } + + if (weboCtxConf.setTargeting === false) { + return {}; + } + + try { + const formattedProfile = profile; + const r = adUnitsCodes.reduce((rp, adUnitCode) => { + if (adUnitCode) { + rp[adUnitCode] = formattedProfile; + } + return rp; + }, {}); + return r; + } catch (e) { + utils.logError('unable to format weborama rtd targeting data', e); + return {}; + } +} + +/** set bigsea contextual profile on module state + * if the profile is empty, will store the default profile + * @param {null|Object} data + * @returns {void} + */ +export function setBigseaContextualProfile(data) { + if (data && Object.keys(data).length > 0) { + _bigseaContextualProfile = data; + } +} + +/** onSuccess callback type + * @callback successCallback + * @param {null|Object} data + * @returns {void} + */ + +/** onDone callback type + * @callback doneCallback + * @returns {void} + */ + +/** Fetch Bigsea Contextual Profile + * @param {WeboCtxConf} weboCtxConf + * @param {successCallback} onSuccess callback + * @param {doneCallback} onDone callback + * @returns {void} + */ +function fetchContextualProfile(weboCtxConf, onSuccess, onDone) { + const targetURL = weboCtxConf.targetURL || document.URL; + const token = weboCtxConf.token; + + let queryString = ''; + queryString = utils.tryAppendQueryString(queryString, 'token', token); + queryString = utils.tryAppendQueryString(queryString, 'url', targetURL); + + const url = 'https://ctx.weborama.com/api/profile?' + queryString; + + ajax(url, { + success: function (response, req) { + if (req.status === 200) { + try { + const data = JSON.parse(response); + onSuccess(data); + onDone(); + } catch (e) { + onDone(); + utils.logError('unable to parse weborama data', e); + } + } else if (req.status === 204) { + onDone(); + } + }, + error: function () { + onDone(); + utils.logError('unable to get weborama data'); + } + }, + null, + { + method: 'GET', + withCredentials: false, + }); +} + +/** Initialize module + * @param {object} moduleConfig + * @return {boolean} true if module was initialized with success + */ +function init(moduleConfig) { + _bigseaContextualProfile = null; + + moduleConfig = moduleConfig || {}; + const moduleParams = moduleConfig.params || {}; + const weboCtxConf = moduleParams.weboCtxConf || {}; + + if (weboCtxConf.token) { + fetchContextualProfile(weboCtxConf, setBigseaContextualProfile, + () => utils.logMessage('fetchContextualProfile on init is done')); + } else { + utils.logError('missing param "token" for weborama rtd module initialization'); + return false; + } + + return true; +} + +export const weboramaSubmodule = { + name: SUBMODULE_NAME, + init: init, + getTargetingData: getTargetingData, +}; + +submodule(MODULE_NAME, weboramaSubmodule); diff --git a/modules/weboramaRtdProvider.md b/modules/weboramaRtdProvider.md new file mode 100644 index 00000000000..e7b9b96d668 --- /dev/null +++ b/modules/weboramaRtdProvider.md @@ -0,0 +1,70 @@ +# Weborama Real-Time Data Submodule + +``` +Module Name: Weborama Rtd Provider +Module Type: Rtd Provider +Maintainer: prebid-support@weborama.com +``` + +# Description + +Weborama provides a Semantic AI Contextual API that classifies in Real-time a web page seen by a web user within generic and custom topics. It enables publishers to better monetize their inventory and unlock it to programmatic. + +ORTB2 compliant and FPD support for Prebid versions < 4.29 + +Contact prebid-support@weborama.com for information. + +### Publisher Usage + +Compile the Weborama RTD module into your Prebid build: + +`gulp build --modules=rtdModule,weboramaRtdProvider` + +Add the Weborama RTD provider to your Prebid config. + +```javascript +pbjs.setConfig( + ... + realTimeData: { + auctionDelay: 1000, + dataProviders: [ + { + name: "weborama", + waitForIt: true, + params: { + weboCtxConf: { + setTargeting: true, + token: "<>", + targetURL: "..." // default is document.URL + } + } + } + ] + } + ... +} +``` + +### Parameter Descriptions for the Weborama Configuration Section + +| Name |Type | Description | Notes | +| :------------ | :------------ | :------------ |:------------ | +| name | String | Real time data module name | Mandatory. Always 'Weborama' | +| waitForIt | Boolean | Mandatory. Required to ensure that the auction is delayed until prefetch is complete | Optional. Defaults to false but recommended to true | +| params | Object | | Optional | +| params.weboCtxConf | Object | Weborama Contextual Configuration | Optional | +| params.weboCtxConf.token | String | Security Token provided by Weborama, unique per client | Mandatory | +| params.weboCtxConf.targetURL | String | Url to be profiled in the contextual api | Optional. Defaults to `document.URL` | +| params.weboCtxConf.defaultProfile | Object | default value of the profile to be used when there are no response from contextual api (such as timeout)| Optional. Default is `{}` | +| params.weboCtxConf.setTargeting|Boolean|If true, will use the contextual profile to set the gam targeting of all adunits managed by prebid.js| Optional. Default is *true*.| +| params.weboCtxConf.setOrtb2|Boolean|If true, will use the contextual profile to set the ortb2 configuration on `site.ext.data`| Optional. Default is *false*.| + +### Testing + +To view an example of available segments returned by Weborama's backends: + +`gulp serve --modules=rtdModule,weboramaRtdProvider,appnexusBidAdapter` + +and then point your browser at: + +`http://localhost:9999/integrationExamples/gpt/weboramaRtdProvider_example.html` diff --git a/test/spec/modules/weboramaRtdProvider_spec.js b/test/spec/modules/weboramaRtdProvider_spec.js new file mode 100644 index 00000000000..155f26990a7 --- /dev/null +++ b/test/spec/modules/weboramaRtdProvider_spec.js @@ -0,0 +1,288 @@ +import { setBigseaContextualProfile, weboramaSubmodule } from 'modules/weboramaRtdProvider.js'; +import { server } from 'test/mocks/xhr.js'; +import {config} from 'src/config.js'; + +const responseHeader = {'Content-Type': 'application/json'}; + +// TODO fix it + +describe('weboramaRtdProvider', function() { + describe('weboramaSubmodule', function() { + it('successfully instantiates and call contextual api', function () { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + } + } + }; + + expect(weboramaSubmodule.init(moduleConfig)).to.equal(true); + + let request = server.requests[0]; + + expect(request.url).to.equal('https://ctx.weborama.com/api/profile?token=foo&url=https%3A%2F%2Fprebid.org&'); + expect(request.method).to.equal('GET') + }); + it('instantiate without token should fail', function () { + const moduleConfig = { + params: { + weboCtxConf: {} + } + }; + expect(weboramaSubmodule.init(moduleConfig)).to.equal(false); + }); + }); + + describe('Add Contextual Data', function() { + beforeEach(function() { + let conf = { + site: { + ext: { + data: { + inventory: ['value1'] + } + } + }, + user: { + ext: { + data: { + visitor: ['value2'] + } + } + }, + cur: ['USD'] + }; + + config.setConfig({ortb2: conf}); + }); + it('should set targeting and ortb2 if omit setTargeting', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setOrtb2: true, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + webo_ds: ['baz'], + }; + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': data, + 'adunit2': data, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data.webo_ctx).to.deep.equal(data.webo_ctx); + expect(ortb2.site.ext.data.webo_ds).to.deep.equal(data.webo_ds); + }); + + it('should set targeting and ortb2 with setTargeting=true', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: true, + setOrtb2: true, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + webo_ds: ['baz'], + }; + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': data, + 'adunit2': data, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data.webo_ctx).to.deep.equal(data.webo_ctx); + expect(ortb2.site.ext.data.webo_ds).to.deep.equal(data.webo_ds); + }); + it('should set targeting and ortb2 only webo_ctx with setTargeting=true', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: true, + setOrtb2: true, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + }; + + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': data, + 'adunit2': data, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data.webo_ctx).to.deep.equal(data.webo_ctx); + expect(ortb2.site.ext.data).to.not.have.property('webo_ds'); + }); + it('should set only targeting and not ortb2 with setTargeting=true and setOrtb2=false', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: true, + setOrtb2: false, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + }; + + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': data, + 'adunit2': data, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data).to.not.have.property('webo_ctx'); + expect(ortb2.site.ext.data).to.not.have.property('webo_ds'); + }); + it('should set only targeting and not ortb2 with setTargeting=true and omit setOrtb2', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: true, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + }; + + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': data, + 'adunit2': data, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data).to.not.have.property('webo_ctx'); + expect(ortb2.site.ext.data).to.not.have.property('webo_ds'); + }); + + it('should set only ortb2 with setTargeting=false', function() { + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: false, + setOrtb2: true, + } + } + }; + const data = { + webo_ctx: ['foo', 'bar'], + }; + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(200, responseHeader, JSON.stringify(data)); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({}); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data.webo_ctx).to.deep.equal(data.webo_ctx); + expect(ortb2.site.ext.data).to.not.have.property('webo_ds'); + }); + it('should use default profile in case of api error', function() { + const defaultProfile = { + webo_ctx: ['baz'], + }; + const moduleConfig = { + params: { + weboCtxConf: { + token: 'foo', + targetURL: 'https://prebid.org', + setTargeting: true, + defaultProfile: defaultProfile, + } + } + }; + + const adUnitsCodes = ['adunit1', 'adunit2']; + weboramaSubmodule.init(moduleConfig); + + let request = server.requests[0]; + request.respond(500, responseHeader); + + const targeting = weboramaSubmodule.getTargetingData(adUnitsCodes, moduleConfig); + + expect(targeting).to.deep.equal({ + 'adunit1': defaultProfile, + 'adunit2': defaultProfile, + }); + + const ortb2 = config.getConfig('ortb2'); + + expect(ortb2.site.ext.data).to.not.have.property('webo_ctx'); + expect(ortb2.site.ext.data).to.not.have.property('webo_ds'); + }); + }); +}); From 5f6881cec1f16e91b2be80d23a29754cb43a61ff Mon Sep 17 00:00:00 2001 From: adquery <89853721+adquery@users.noreply.github.com> Date: Wed, 22 Sep 2021 15:54:05 +0200 Subject: [PATCH 02/84] New bidder adapter - Adquery (#7441) * init adapter * implemented buildRequests * new adquery adapter * adquery adapter - prepared test * adquery adapter - increase test coverage and minor changes after review * adquery - fixed multi bid and response from server Co-authored-by: m.czerwiak --- modules/adqueryBidAdapter.js | 204 ++++++++++++++++++++ modules/adqueryBidAdapter.md | 32 +++ test/spec/modules/adqueryBidAdapter_spec.js | 185 ++++++++++++++++++ 3 files changed, 421 insertions(+) create mode 100644 modules/adqueryBidAdapter.js create mode 100644 modules/adqueryBidAdapter.md create mode 100644 test/spec/modules/adqueryBidAdapter_spec.js diff --git a/modules/adqueryBidAdapter.js b/modules/adqueryBidAdapter.js new file mode 100644 index 00000000000..bbff7edea47 --- /dev/null +++ b/modules/adqueryBidAdapter.js @@ -0,0 +1,204 @@ +import {registerBidder} from '../src/adapters/bidderFactory.js'; +import {BANNER} from '../src/mediaTypes.js'; +import * as utils from '../src/utils.js'; +import { getStorageManager } from '../src/storageManager.js'; + +const ADQUERY_GVLID = 902; +const ADQUERY_BIDDER_CODE = 'adquery'; +const ADQUERY_BIDDER_DOMAIN_PROTOCOL = 'https'; +const ADQUERY_BIDDER_DOMAIN = 'bidder.adquery.io'; +const ADQUERY_USER_SYNC_DOMAIN = ADQUERY_BIDDER_DOMAIN_PROTOCOL + '://' + ADQUERY_BIDDER_DOMAIN + '/prebid/userSync?1=1'; +const ADQUERY_DEFAULT_CURRENCY = 'PLN'; +const ADQUERY_NET_REVENUE = true; +const ADQUERY_TTL = 360; +const storage = getStorageManager(ADQUERY_GVLID); + +/** @type {BidderSpec} */ +export const spec = { + code: ADQUERY_BIDDER_CODE, + gvlid: ADQUERY_GVLID, + supportedMediaTypes: [BANNER], + + /** f + * @param {object} bid + * @return {boolean} + */ + isBidRequestValid: (bid) => { + return !!(bid && bid.params && bid.params.placementId) + }, + + /** + * @param {BidRequest[]} bidRequests + * @param {*} bidderRequest + * @return {ServerRequest} + */ + buildRequests: (bidRequests, bidderRequest) => { + const requests = []; + for (let i = 0, len = bidRequests.length; i < len; i++) { + const request = { + method: 'POST', + url: ADQUERY_BIDDER_DOMAIN_PROTOCOL + '://' + ADQUERY_BIDDER_DOMAIN + '/prebid/bid', + data: buildRequest(bidRequests[i], bidderRequest), + options: { + withCredentials: false, + crossOrigin: true + } + }; + requests.push(request); + } + return requests; + }, + + /** + * @param {*} response + * @param {ServerRequest} request + * @return {Bid[]} + */ + interpretResponse: (response, request) => { + utils.logInfo(request); + utils.logInfo(response); + + const res = response && response.body && response.body.data; + let bidResponses = []; + + if (!res) { + return []; + } + + const bidResponse = { + requestId: res.requestId, + cpm: res.cpm, + width: res.mediaType.width, + height: res.mediaType.height, + creativeId: res.creationId, + dealId: res.dealid || '', + currency: res.currency || ADQUERY_DEFAULT_CURRENCY, + netRevenue: ADQUERY_NET_REVENUE, + ttl: ADQUERY_TTL, + referrer: '', + ad: '' + res.tag, + mediaType: res.mediaType.name || 'banner', + meta: { + advertiserDomains: res.adDomains && res.adDomains.length ? res.adDomains : [], + mediaType: res.mediaType.name || 'banner', + } + }; + bidResponses.push(bidResponse); + utils.logInfo('bidResponses', bidResponses); + + return bidResponses; + }, + + /** + * @param {TimedOutBid} timeoutData + */ + onTimeout: (timeoutData) => { + if (timeoutData == null) { + return; + } + utils.logInfo('onTimeout ', timeoutData); + let params = { + bidder: timeoutData.bidder, + bId: timeoutData.bidId, + adUnitCode: timeoutData.adUnitCode, + timeout: timeoutData.timeout, + auctionId: timeoutData.auctionId, + }; + let adqueryRequestUrl = utils.buildUrl({ + protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, + hostname: ADQUERY_BIDDER_DOMAIN, + pathname: '/prebid/eventTimeout', + search: params + }); + utils.triggerPixel(adqueryRequestUrl); + }, + + /** + * @param {Bid} bid + */ + onBidWon: (bid) => { + utils.logInfo('onBidWon', bid); + const bidString = JSON.stringify(bid); + const encodedBuf = window.btoa(bidString); + + let params = { + q: encodedBuf, + }; + let adqueryRequestUrl = utils.buildUrl({ + protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, + hostname: ADQUERY_BIDDER_DOMAIN, + pathname: '/prebid/eventBidWon', + search: params + }); + utils.triggerPixel(adqueryRequestUrl); + }, + + /** + * @param {Bid} bid + */ + onSetTargeting: (bid) => { + utils.logInfo('onSetTargeting', bid); + + let params = { + bidder: bid.bidder, + width: bid.width, + height: bid.height, + bid: bid.adId, + mediaType: bid.mediaType, + cpm: bid.cpm, + requestId: bid.requestId, + adUnitCode: bid.adUnitCode + }; + + let adqueryRequestUrl = utils.buildUrl({ + protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, + hostname: ADQUERY_BIDDER_DOMAIN, + pathname: '/prebid/eventSetTargeting', + search: params + }); + utils.triggerPixel(adqueryRequestUrl); + }, + getUserSyncs: (syncOptions, serverResponses, gdprConsent, uspConsent) => { + let syncUrl = ADQUERY_USER_SYNC_DOMAIN; + if (gdprConsent && gdprConsent.consentString) { + if (typeof gdprConsent.gdprApplies === 'boolean') { + syncUrl += `&gdpr=${Number(gdprConsent.gdprApplies)}&gdpr_consent=${gdprConsent.consentString}`; + } else { + syncUrl += `&gdpr=0&gdpr_consent=${gdprConsent.consentString}`; + } + } + if (uspConsent && uspConsent.consentString) { + syncUrl += `&ccpa_consent=${uspConsent.consentString}`; + } + return [{ + type: 'image', + url: syncUrl + }]; + } + +}; +function buildRequest(validBidRequests, bidderRequest) { + let qid = Math.random().toString(36).substring(2) + Date.now().toString(36); + let bid = validBidRequests; + + if (storage.getDataFromLocalStorage('qid')) { + qid = storage.getDataFromLocalStorage('qid'); + } else { + storage.setDataInLocalStorage('qid', qid); + } + + return { + placementCode: bid.params.placementId, + auctionId: bid.auctionId, + qid: qid, + type: bid.params.type, + adUnitCode: bid.adUnitCode, + bidId: bid.bidId, + bidder: bid.bidder, + bidderRequestId: bid.bidderRequestId, + bidRequestsCount: bid.bidRequestsCount, + bidderRequestsCount: bid.bidderRequestsCount, + }; +} + +registerBidder(spec); diff --git a/modules/adqueryBidAdapter.md b/modules/adqueryBidAdapter.md new file mode 100644 index 00000000000..e8b68e30406 --- /dev/null +++ b/modules/adqueryBidAdapter.md @@ -0,0 +1,32 @@ +# Overview + +Module Name: Adquery Bidder Adapter +Module Type: Bidder Adapter +Maintainer: prebid@adquery.com + +# Description + +Module that connects to Adquery's demand sources. + +# Test Parameters +``` + var adUnits = [ + { + code: 'banner-adquery-div', + mediaTypes: { + banner: { + sizes: [[300, 250]], + } + }, + bids: [ + { + bidder: 'adquery', + params: { + placementId: '6d93f2a0e5f0fe2cc3a6e9e3ade964b43b07f897', + type: 'banner300x250' + } + } + ] + } + ]; +``` diff --git a/test/spec/modules/adqueryBidAdapter_spec.js b/test/spec/modules/adqueryBidAdapter_spec.js new file mode 100644 index 00000000000..4285377e8a7 --- /dev/null +++ b/test/spec/modules/adqueryBidAdapter_spec.js @@ -0,0 +1,185 @@ +import { expect } from 'chai' +import { spec } from 'modules/adqueryBidAdapter.js' +import { newBidder } from 'src/adapters/bidderFactory.js' +import * as utils from '../../../src/utils'; + +describe('adqueryBidAdapter', function () { + const adapter = newBidder(spec) + let bidRequest = { + bidder: 'adquery', + params: { + placementId: '6d93f2a0e5f0fe2cc3a6e9e3ade964b43b07f897', + type: 'banner300x250' + }, + mediaTypes: { + banner: { + sizes: [[300, 250]], + } + } + } + + let expectedResponse = { + 'body': { + 'data': + { + 'requestId': 1, + 'emission_id': 1, + 'eventTracker': 'https://example.com', + 'externalEmissionCodes': 'https://example.com', + 'impressionTracker': 'https://example.com', + 'viewabilityTracker': 'https://example.com', + 'clickTracker': 'https://example.com', + 'link': 'https://example.com', + 'logo': 'https://example.com', + 'medias': [ + { + 'src': 'banner/2021-04-09/938', + 'ext': 'zip', + 'type': 3, + } + ], + 'domain': 'https://example.com', + 'urlAdq': 'https://example.com', + 'creationId': 1, + 'currency': 'PLN', + 'adDomains': ['https://example.com'], + 'tag': ' ', + 'adqLib': 'https://example.com/js/example.js', + 'mediaType': {'width': 300, 'height': 250, 'name': 'banner', 'type': 'banner300x250'}, + 'cpm': 2.5, + 'meta': { + 'advertiserDomains': ['example.com'], + 'mediaType': 'banner', + } + } + } + } + describe('codes', function () { + it('should return a bidder code of adquery', function () { + expect(spec.code).to.equal('adquery') + }) + }) + + describe('isBidRequestValid', function () { + let inValidBid = Object.assign({}, bidRequest) + delete inValidBid.params + it('should return true if all params present', function () { + expect(spec.isBidRequestValid(bidRequest)).to.equal(true) + }) + + it('should return false if any parameter missing', function () { + expect(spec.isBidRequestValid(inValidBid)).to.be.false + }) + }) + + describe('buildRequests', function () { + let req = spec.buildRequests([ bidRequest ], { refererInfo: { } })[0] + let rdata + + it('should return request object', function () { + expect(req).to.not.be.null + }) + + it('should build request data', function () { + expect(req.data).to.not.be.null + }) + + it('should include one request', function () { + rdata = req.data; + expect(rdata.data).to.not.be.null + }) + + it('should include placementCode', function () { + expect(rdata.placementCode).not.be.null + }) + + it('should include qid', function () { + expect(rdata.qid).not.be.null + }) + + it('should include type', function () { + expect(rdata.type !== null).not.be.null + }) + + it('should include all publisher params', function () { + expect(rdata.type !== null && rdata.placementCode !== null).to.be.true + }) + + it('should include bidder', function () { + expect(rdata.bidder !== null).to.be.true + }) + }) + + describe('interpretResponse', function () { + it('should get the correct bid response', function () { + let result = spec.interpretResponse(expectedResponse) + expect(result).to.be.an('array') + }) + + it('validate response params', function() { + const newResponse = spec.interpretResponse(expectedResponse, bidRequest); + expect(newResponse[0].requestId).to.be.equal(1) + }); + it('handles empty bid response', function () { + let response = { + body: {} + }; + let result = spec.interpretResponse(response); + expect(result.length).to.equal(0); + }) + }) + + describe('getUserSyncs', function () { + it('should return iframe sync', function () { + let sync = spec.getUserSyncs() + expect(sync.length).to.equal(1) + expect(sync[0].type === 'iframe') + expect(typeof sync[0].url === 'string') + }) + + it('Should return array of objects with proper sync config , include GDPR', function() { + const syncData = spec.getUserSyncs({}, {}, { + consentString: 'ALL', + gdprApplies: true, + }, {}); + expect(syncData).to.be.an('array').which.is.not.empty; + expect(syncData[0]).to.be.an('object') + expect(syncData[0].type).to.be.a('string') + expect(syncData[0].type).to.equal('image') + }); + }) + + describe('test onBidWon function', function () { + beforeEach(function() { + sinon.stub(utils, 'triggerPixel'); + }); + afterEach(function() { + utils.triggerPixel.restore(); + }); + it('exists and is a function', () => { + expect(spec.onBidWon).to.exist.and.to.be.a('function'); + }); + it('should return nothing', function () { + var response = spec.onBidWon({}); + expect(response).to.be.an('undefined') + expect(utils.triggerPixel.called).to.equal(true); + }); + }) + + describe('onTimeout', function () { + const timeoutData = [{ + timeout: null + }]; + + it('should exists and be a function', () => { + expect(spec.onTimeout).to.exist.and.to.be.a('function'); + }); + it('should include timeoutData', function () { + expect(spec.onTimeout(timeoutData)).to.be.undefined; + }) + }); + + it(`onSetTargeting is present and type function`, function () { + expect(spec.onSetTargeting).to.exist.and.to.be.a('function') + }); +}) From 6f556543069b8f8158ef70fa230128fc07dcf286 Mon Sep 17 00:00:00 2001 From: Monis Qadri Date: Wed, 22 Sep 2021 19:31:40 +0530 Subject: [PATCH 03/84] medianetBidAdapter sending ortb2imp in bid request (#7443) Co-authored-by: monis.q --- modules/medianetBidAdapter.js | 5 ++ test/spec/modules/medianetBidAdapter_spec.js | 63 +++++++++++++++++++- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/modules/medianetBidAdapter.js b/modules/medianetBidAdapter.js index 3b7e555cc72..d78f4a70e2c 100644 --- a/modules/medianetBidAdapter.js +++ b/modules/medianetBidAdapter.js @@ -179,6 +179,11 @@ function slotParams(bidRequest) { }, all: bidRequest.params }; + + if (bidRequest.ortb2Imp) { + params.ortb2Imp = bidRequest.ortb2Imp; + } + let bannerSizes = utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes') || []; const videoInMediaType = utils.deepAccess(bidRequest, 'mediaTypes.video') || {}; diff --git a/test/spec/modules/medianetBidAdapter_spec.js b/test/spec/modules/medianetBidAdapter_spec.js index adb9663ba7c..8589c3b404f 100644 --- a/test/spec/modules/medianetBidAdapter_spec.js +++ b/test/spec/modules/medianetBidAdapter_spec.js @@ -1,4 +1,4 @@ -import {expect} from 'chai'; +import {expect, assert} from 'chai'; import {spec} from 'modules/medianetBidAdapter.js'; import { makeSlot } from '../integration/faker/googletag.js'; import { config } from 'src/config.js'; @@ -99,6 +99,56 @@ let VALID_BID_REQUEST = [{ 'auctionId': 'aafabfd0-28c0-4ac0-aa09-99689e88b81d', 'bidRequestsCount': 1 }], + VALID_BID_REQUEST_WITH_ORTB2 = [{ + 'bidder': 'medianet', + 'params': { + 'crid': 'crid', + 'cid': 'customer_id', + 'site': { + 'page': 'http://media.net/prebidtest', + 'domain': 'media.net', + 'ref': 'http://media.net/prebidtest', + 'isTop': true + } + }, + 'adUnitCode': 'div-gpt-ad-1460505748561-0', + 'transactionId': '277b631f-92f5-4844-8b19-ea13c095d3f1', + 'mediaTypes': { + 'banner': { + 'sizes': [[300, 250]], + } + }, + 'bidId': '28f8f8130a583e', + 'bidderRequestId': '1e9b1f07797c1c', + 'auctionId': 'aafabfd0-28c0-4ac0-aa09-99689e88b81d', + 'ortb2Imp': { 'ext': { 'data': { 'pbadslot': '/12345/my-gpt-tag-0' } } }, + 'bidRequestsCount': 1 + }, { + 'bidder': 'medianet', + 'params': { + 'crid': 'crid', + 'cid': 'customer_id', + 'site': { + 'page': 'http://media.net/prebidtest', + 'domain': 'media.net', + 'ref': 'http://media.net/prebidtest', + 'isTop': true + } + }, + 'adUnitCode': 'div-gpt-ad-1460505748561-123', + 'transactionId': 'c52a5c62-3c2b-4b90-9ff8-ec1487754822', + 'mediaTypes': { + 'banner': { + 'sizes': [[300, 251]], + } + }, + 'sizes': [[300, 251]], + 'bidId': '3f97ca71b1e5c2', + 'bidderRequestId': '1e9b1f07797c1c', + 'auctionId': 'aafabfd0-28c0-4ac0-aa09-99689e88b81d', + 'ortb2Imp': { 'ext': { 'data': { 'pbadslot': '/12345/my-gpt-tag-0' } } }, + 'bidRequestsCount': 1 + }], VALID_BID_REQUEST_WITH_USERID = [{ 'bidder': 'medianet', 'params': { @@ -1247,6 +1297,17 @@ describe('Media.net bid adapter', function () { expect(JSON.parse(bidreq.data)).to.deep.equal(VALID_PAYLOAD_WITH_CRID); }); + it('should have valid ortb2Imp param present in bid request', function() { + let bidreq = spec.buildRequests(VALID_BID_REQUEST_WITH_ORTB2, VALID_AUCTIONDATA); + let actual = JSON.parse(bidreq.data).imp[0].ortb2Imp; + const expected = VALID_BID_REQUEST_WITH_ORTB2[0].ortb2Imp + assert.equal(JSON.stringify(actual), JSON.stringify(expected)) + + bidreq = spec.buildRequests(VALID_BID_REQUEST, VALID_AUCTIONDATA); + actual = JSON.parse(bidreq.data).imp[0].ortb2Imp; + assert.equal(actual, undefined) + }); + it('should have userid in bid request', function () { let bidReq = spec.buildRequests(VALID_BID_REQUEST_WITH_USERID, VALID_AUCTIONDATA); expect(JSON.parse(bidReq.data)).to.deep.equal(VALID_PAYLOAD_WITH_USERID); From 46b12294ad7da21ee71fc60686d46f264f460f96 Mon Sep 17 00:00:00 2001 From: Monis Qadri Date: Wed, 22 Sep 2021 20:05:17 +0530 Subject: [PATCH 04/84] removed pr logs and fixed sampling in medianetAnalyticsAdapter (#7423) Co-authored-by: monis.q --- modules/medianetAnalyticsAdapter.js | 105 +++--------------- .../modules/medianetAnalyticsAdapter_spec.js | 46 ++++++-- 2 files changed, 53 insertions(+), 98 deletions(-) diff --git a/modules/medianetAnalyticsAdapter.js b/modules/medianetAnalyticsAdapter.js index cb65a6afc54..45fb39d8c82 100644 --- a/modules/medianetAnalyticsAdapter.js +++ b/modules/medianetAnalyticsAdapter.js @@ -42,17 +42,10 @@ const VALID_URL_KEY = ['canonical_url', 'og_url', 'twitter_url']; const DEFAULT_URL_KEY = 'page'; const LOG_TYPE = { - AP: 'AP', - PR: 'PR', APPR: 'APPR', RA: 'RA' }; -const BATCHING = { - SINGLE: 'SINGLE', - MULTI: 'MULTI' -} - let auctions = {}; let config; let pageDetails; @@ -66,7 +59,6 @@ class ErrorLogger { this.project = 'prebidanalytics'; this.dn = pageDetails.domain || ''; this.requrl = pageDetails.requrl || ''; - this.event = this.event; this.pbversion = PREBID_VERSION; this.cid = config.cid || ''; this.rd = additionalData; @@ -89,18 +81,10 @@ class Configure { this.gdprConsent = undefined; this.gdprApplies = undefined; this.uspConsent = undefined; - this.pixelWaitTime = 0; - this.apLoggingPct = 0; - this.prLoggingPct = 0; - this.batching = BATCHING.SINGLE; this.shouldBeLogged = {}; this.mnetDebugConfig = ''; } - set publisherLper(plper) { - this.pubLper = plper; - } - getLoggingData() { return { cid: this.cid, @@ -139,20 +123,6 @@ class Configure { if (!isNaN(parseInt(response.percentage, 10))) { this.loggingPercent = response.percentage; } - - if (!isNaN(parseInt(response.pixelwaittime, 10))) { - this.pixelWaitTime = response.pixelwaittime; - } - - if (!isNaN(parseInt(response.aplper, 10))) { - this.apLoggingPct = response.aplper; - this.batching = BATCHING.MULTI; - } - - if (!isNaN(parseInt(response.prlper, 10))) { - this.prLoggingPct = response.prlper; - this.batching = BATCHING.MULTI; - } } overrideDomainLevelData(response) { @@ -268,18 +238,14 @@ class AdSlot { this.context = context; this.adext = adext; this.logged = {}; - this.logged[LOG_TYPE.PR] = false; - this.logged[LOG_TYPE.AP] = false; - this.logged[LOG_TYPE.APPR] = false; this.targeting = undefined; this.medianetPresent = 0; } getShouldBeLogged(logType) { if (!config.shouldBeLogged.hasOwnProperty(logType)) { - config.shouldBeLogged[logType] = isSampled(logType); + config.shouldBeLogged[logType] = isSampled(); } - config.shouldBeLogged[logType] = isSampled(logType); return config.shouldBeLogged[logType]; } @@ -343,7 +309,7 @@ class Bid { bdp: this.cpm, cbdp: this.dfpbd, dfpbd: this.dfpbd, - szs: this.allMediaTypeSizes.map(sz => sz.join('x')).join('|'), + szs: this.allMediaTypeSizes.join('|'), size: this.size, mtype: this.mediaType, dId: this.dealId, @@ -475,10 +441,9 @@ function addAddSlots(auctionId, adUnits, tmax) { adext = utils.isEmpty(adext) ? undefined : adext; oSizes.banner = oSizes.banner.filter(utils.uniques); oSizes.video = oSizes.video.filter(utils.uniques); - oSizes.native = mediaTypeMap.native === 1 ? [[1, 1]] : []; + oSizes.native = mediaTypeMap.native === 1 ? [[1, 1].join('x')] : []; const allMediaTypeSizes = [].concat(oSizes.banner, oSizes.native, oSizes.video); const mediaTypes = Object.keys(mediaTypeMap).join('|'); - auctions[auctionId].addSlot({adUnitCode, supplyAdCode, mediaTypes, allMediaTypeSizes, context, tmax, adext}); }); } @@ -518,7 +483,11 @@ function _getSizes(mediaTypes, sizes) { if (playerSize.length === 2) { video = [playerSize] } - return { banner, native, video } + return { + banner: banner.map(size => size.join('x')), + native: native.map(size => size.join('x')), + video: video.map(size => size.join('x')) + } } function bidResponseHandler(bid) { @@ -593,18 +562,12 @@ function bidTimeoutHandler(timedOutBids) { }) } -function auctionEndHandler({auctionId, auctionEnd, adUnitCodes}) { +function auctionEndHandler({auctionId, auctionEnd}) { if (!(auctions[auctionId] instanceof Auction)) { return; } auctions[auctionId].status = AUCTION_COMPLETED; auctions[auctionId].auctionEndTime = auctionEnd; - - if (config.batching === BATCHING.MULTI) { - adUnitCodes.forEach(function (adUnitCode) { - sendEvent(auctionId, adUnitCode, LOG_TYPE.PR); - }); - } } function setTargetingHandler(params) { @@ -639,30 +602,11 @@ function setTargetingHandler(params) { bid.height = utils.deepAccess(winningBid, 'height'); } }); - sendEvent(auctionId, adunit, getLogType()); + sendEvent(auctionId, adunit, LOG_TYPE.APPR); } } } -function getLogType() { - if (config.batching === BATCHING.SINGLE) { - return LOG_TYPE.APPR; - } - return LOG_TYPE.AP; -} - -function setBidderDone(params) { - if (config.pixelWaitTime != null && config.pixelWaitTime > 0) { - setTimeout(fireApAfterWait, config.pixelWaitTime, params) - } -} - -function fireApAfterWait(params) { - params.bids.forEach(function (adUnit) { - sendEvent(params.auctionId, adUnit.adUnitCode, LOG_TYPE.AP); - }); -} - function bidWonHandler(bid) { const { requestId, auctionId, adUnitCode } = bid; if (!(auctions[auctionId] instanceof Auction)) { @@ -677,20 +621,8 @@ function bidWonHandler(bid) { sendEvent(auctionId, adUnitCode, LOG_TYPE.RA); } -function isSampled(logType) { - return Math.random() * 100 < parseFloat(getLogPercentage(logType)); -} - -function getLogPercentage(logType) { - let logPercentage = config.loggingPercent; - if (config.batching === BATCHING.MULTI) { - if (logType === LOG_TYPE.AP) { - logPercentage = config.apLoggingPct; - } else if (logType === LOG_TYPE.PR) { - logPercentage = config.prLoggingPct; - } - } - return logPercentage; +function isSampled() { + return Math.random() * 100 < parseFloat(config.loggingPercent); } function isValidAuctionAdSlot(acid, adtag) { @@ -711,13 +643,8 @@ function sendEvent(id, adunit, logType) { function fireApPrLog(auctionId, adUnitName, logType) { const adSlot = auctions[auctionId].adSlots[adUnitName]; if (adSlot.getShouldBeLogged(logType) && !adSlot.logged[logType]) { - if (config.batching === BATCHING.SINGLE) { - adSlot.logged[LOG_TYPE.AP] = true; - adSlot.logged[LOG_TYPE.PR] = true; - } else { - adSlot.logged[logType] = true; - } fireAuctionLog(auctionId, adUnitName, logType); + adSlot.logged[logType] = true; } } @@ -844,10 +771,6 @@ let medianetAnalytics = Object.assign(adapter({URL, analyticsType}), { setTargetingHandler(args); break; } - case CONSTANTS.EVENTS.BIDDER_DONE : { - setBidderDone(args); - break; - } case CONSTANTS.EVENTS.BID_WON: { bidWonHandler(args); break; @@ -868,7 +791,7 @@ medianetAnalytics.enableAnalytics = function (configuration) { pageDetails = new PageDetail(); config = new Configure(configuration.options.cid); - config.publisherLper = configuration.options.sampling || ''; + config.pubLper = configuration.options.sampling || ''; config.init(); configuration.options.sampling = 1; medianetAnalytics.originEnableAnalytics(configuration); diff --git a/test/spec/modules/medianetAnalyticsAdapter_spec.js b/test/spec/modules/medianetAnalyticsAdapter_spec.js index 41a6338225e..a0a62710a56 100644 --- a/test/spec/modules/medianetAnalyticsAdapter_spec.js +++ b/test/spec/modules/medianetAnalyticsAdapter_spec.js @@ -11,10 +11,12 @@ const { const MOCK = { Ad_Units: [{'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'banner': {'sizes': [[300, 250]]}}, 'bids': [], 'ext': {'prop1': 'value1'}}], MULTI_FORMAT_TWIN_AD_UNITS: [{'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'banner': {'sizes': [[300, 250]]}, 'native': {'image': {'required': true, 'sizes': [150, 50]}}}, 'bids': [], 'ext': {'prop1': 'value1'}}, {'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'video': {'playerSize': [640, 480], 'context': 'instream'}}, 'bids': [], 'ext': {'prop1': 'value1'}}], + TWIN_AD_UNITS: [{'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'banner': {'sizes': [[300, 100]]}}, 'ask': '300x100', 'bids': [{'bidder': 'bidder1', 'params': {'siteId': '451465'}}]}, {'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'banner': {'sizes': [[300, 250], [300, 100]]}}, 'bids': [{'bidder': 'medianet', 'params': {'cid': 'TEST_CID', 'crid': '451466393'}}]}, {'code': 'div-gpt-ad-1460505748561-0', 'mediaTypes': {'banner': {'sizes': [[300, 250]]}}, 'bids': [{'bidder': 'bidder1', 'params': {'siteId': '451466'}}]}], AUCTION_INIT: {'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'timestamp': 1584563605739, 'timeout': 6000}, AUCTION_INIT_WITH_FLOOR: {'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'timestamp': 1584563605739, 'timeout': 6000, 'bidderRequests': [{'bids': [{ 'floorData': {'enforcements': {'enforceJS': true}} }]}]}, BID_REQUESTED: {'bidderCode': 'medianet', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'bids': [{'bidder': 'medianet', 'params': {'cid': 'TEST_CID', 'crid': '451466393'}, 'mediaTypes': {'banner': {'sizes': [[300, 250]], 'ext': ['asdads']}}, 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'sizes': [[300, 250]], 'bidId': '28248b0e6aece2', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'src': 'client'}], 'auctionStart': 1584563605739, 'timeout': 6000, 'uspConsent': '1YY', 'start': 1584563605743}, MULTI_FORMAT_BID_REQUESTED: {'bidderCode': 'medianet', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'bids': [{'bidder': 'medianet', 'params': {'cid': 'TEST_CID', 'crid': '451466393'}, 'mediaTypes': {'banner': {'sizes': [[300, 250]]}, 'video': {'playerSize': [640, 480], 'context': 'instream'}, 'native': {'image': {'required': true, 'sizes': [150, 50]}, 'title': {'required': true, 'len': 80}}}, 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'sizes': [[300, 250]], 'bidId': '28248b0e6aece2', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'src': 'client'}], 'auctionStart': 1584563605739, 'timeout': 6000, 'uspConsent': '1YY', 'start': 1584563605743}, + TWIN_AD_UNITS_BID_REQUESTED: [{'bidderCode': 'bidder1', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'bidderRequestId': '16f0746ff657b5', 'bids': [{'bidder': 'bidder1', 'params': {'siteId': '451465'}, 'mediaTypes': {'banner': {'sizes': [[300, 100]]}}, 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'transactionId': '9615b5d1-7a4f-4c65-9464-4178b91da9e3', 'sizes': [[300, 100]], 'bidId': '2984d18e18bdfe', 'bidderRequestId': '16f0746ff657b5', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'src': 'client', 'bidRequestsCount': 3, 'bidderRequestsCount': 2, 'bidderWinsCount': 0}, {'bidder': 'bidder1', 'params': {'siteId': '451466'}, 'mediaTypes': {'banner': {'sizes': [[300, 250]]}}, 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'transactionId': '8bd7c9f2-0fe6-4ac5-8f2a-7f4a88af1b71', 'sizes': [[300, 250]], 'bidId': '3dced609066035', 'bidderRequestId': '16f0746ff657b5', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'src': 'client', 'bidRequestsCount': 3, 'bidderRequestsCount': 2, 'bidderWinsCount': 0}], 'auctionStart': 1584563605739, 'timeout': 3000, 'start': 1584563605743}, {'bidderCode': 'medianet', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'bidderRequestId': '4b45d1de1fa8fe', 'bids': [{'bidder': 'medianet', 'params': {'cid': 'TEST_CID', 'crid': '451466393'}, 'mediaTypes': {'banner': {'sizes': [[300, 250], [300, 100]]}}, 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'transactionId': '215c038e-3b6a-465b-8937-d32e2ad8de45', 'sizes': [[300, 250], [300, 100]], 'bidId': '58d34adcb09c99', 'bidderRequestId': '4b45d1de1fa8fe', 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'src': 'client', 'bidRequestsCount': 3, 'bidderRequestsCount': 1, 'bidderWinsCount': 0}], 'auctionStart': 1584563605739, 'timeout': 3000, 'start': 1584563605743}], BID_RESPONSE: {'bidderCode': 'medianet', 'width': 300, 'height': 250, 'adId': '3e6e4bce5c8fb3', 'requestId': '28248b0e6aece2', 'mediaType': 'banner', 'source': 'client', 'ext': {'pvid': 123, 'crid': '321'}, 'no_bid': false, 'cpm': 2.299, 'ad': 'AD_CODE', 'ttl': 180, 'creativeId': 'Test1', 'netRevenue': true, 'currency': 'USD', 'dfp_id': 'div-gpt-ad-1460505748561-0', 'originalCpm': 1.1495, 'originalCurrency': 'USD', 'floorData': {'floorValue': 1.10, 'floorRule': 'banner'}, 'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'responseTimestamp': 1584563606009, 'requestTimestamp': 1584563605743, 'bidder': 'medianet', 'adUnitCode': 'div-gpt-ad-1460505748561-0', 'timeToRespond': 266, 'pbLg': '2.00', 'pbMg': '2.20', 'pbHg': '2.29', 'pbAg': '2.25', 'pbDg': '2.29', 'pbCg': '2.00', 'size': '300x250', 'adserverTargeting': {'hb_bidder': 'medianet', 'hb_adid': '3e6e4bce5c8fb3', 'hb_pb': '2.00', 'hb_size': '300x250', 'hb_source': 'client', 'hb_format': 'banner', 'prebid_test': 1}, 'status': 'rendered', 'params': [{'cid': 'test123', 'crid': '451466393'}]}, AUCTION_END: {'auctionId': '8e0d5245-deb3-406c-96ca-9b609e077ff7', 'auctionEnd': 1584563605739}, SET_TARGETING: {'div-gpt-ad-1460505748561-0': {'prebid_test': '1', 'hb_format': 'banner', 'hb_source': 'client', 'hb_size': '300x250', 'hb_pb': '2.00', 'hb_adid': '3e6e4bce5c8fb3', 'hb_bidder': 'medianet', 'hb_format_medianet': 'banner', 'hb_source_medianet': 'client', 'hb_size_medianet': '300x250', 'hb_pb_medianet': '2.00', 'hb_adid_medianet': '3e6e4bce5c8fb3', 'hb_bidder_medianet': 'medianet'}}, @@ -25,7 +27,7 @@ const MOCK = { } function performAuctionWithFloorConfig() { - events.emit(AUCTION_INIT, {...MOCK.AUCTION_INIT_WITH_FLOOR, adUnits: MOCK.Ad_Units}); + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT_WITH_FLOOR, {adUnits: MOCK.Ad_Units})); events.emit(BID_REQUESTED, MOCK.BID_REQUESTED); events.emit(BID_RESPONSE, MOCK.BID_RESPONSE); events.emit(AUCTION_END, MOCK.AUCTION_END); @@ -34,7 +36,7 @@ function performAuctionWithFloorConfig() { } function performStandardAuctionWithWinner() { - events.emit(AUCTION_INIT, {...MOCK.AUCTION_INIT, adUnits: MOCK.Ad_Units}); + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT, {adUnits: MOCK.Ad_Units})); events.emit(BID_REQUESTED, MOCK.BID_REQUESTED); events.emit(BID_RESPONSE, MOCK.BID_RESPONSE); events.emit(AUCTION_END, MOCK.AUCTION_END); @@ -43,15 +45,23 @@ function performStandardAuctionWithWinner() { } function performMultiFormatAuctionWithNoBid() { - events.emit(AUCTION_INIT, {...MOCK.AUCTION_INIT, adUnits: MOCK.MULTI_FORMAT_TWIN_AD_UNITS}); + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT, {adUnits: MOCK.MULTI_FORMAT_TWIN_AD_UNITS})); events.emit(BID_REQUESTED, MOCK.MULTI_FORMAT_BID_REQUESTED); events.emit(NO_BID, MOCK.NO_BID); events.emit(AUCTION_END, MOCK.AUCTION_END); events.emit(SET_TARGETING, MOCK.NO_BID_SET_TARGETING); } +function performTwinAdUnitAuctionWithNoBid() { + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT, {adUnits: MOCK.TWIN_AD_UNITS})); + MOCK.TWIN_AD_UNITS_BID_REQUESTED.forEach(bidRequested => events.emit(BID_REQUESTED, bidRequested)); + MOCK.TWIN_AD_UNITS_BID_REQUESTED.forEach(bidRequested => bidRequested.bids.forEach(noBid => events.emit(NO_BID, noBid))); + events.emit(AUCTION_END, MOCK.AUCTION_END); + events.emit(SET_TARGETING, MOCK.NO_BID_SET_TARGETING); +} + function performStandardAuctionWithNoBid() { - events.emit(AUCTION_INIT, {...MOCK.AUCTION_INIT, adUnits: MOCK.Ad_Units}); + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT, {adUnits: MOCK.Ad_Units})); events.emit(BID_REQUESTED, MOCK.BID_REQUESTED); events.emit(NO_BID, MOCK.NO_BID); events.emit(AUCTION_END, MOCK.AUCTION_END); @@ -59,17 +69,20 @@ function performStandardAuctionWithNoBid() { } function performStandardAuctionWithTimeout() { - events.emit(AUCTION_INIT, {...MOCK.AUCTION_INIT, adUnits: MOCK.Ad_Units}); + events.emit(AUCTION_INIT, Object.assign({}, MOCK.AUCTION_INIT, {adUnits: MOCK.Ad_Units})); events.emit(BID_REQUESTED, MOCK.BID_REQUESTED); events.emit(BID_TIMEOUT, MOCK.BID_TIMEOUT); events.emit(AUCTION_END, MOCK.AUCTION_END); events.emit(SET_TARGETING, MOCK.NO_BID_SET_TARGETING); } -function getQueryData(url) { +function getQueryData(url, decode = false) { const queryArgs = url.split('?')[1].split('&'); return queryArgs.reduce((data, arg) => { - const [key, val] = arg.split('='); + let [key, val] = arg.split('='); + if (decode) { + val = decodeURIComponent(val); + } if (data[key] !== undefined) { if (!Array.isArray(data[key])) { data[key] = [data[key]]; @@ -149,6 +162,25 @@ describe('Media.net Analytics Adapter', function() { expect(noBidLog.vplcmtt).to.equal('instream'); }); + it('twin ad units should have correct sizes', function() { + performTwinAdUnitAuctionWithNoBid(); + const noBidLog = medianetAnalytics.getlogsQueue().map((log) => getQueryData(log, true))[0]; + const banner = 'banner'; + expect(noBidLog.pvnm).to.have.ordered.members(['-2', 'bidder1', 'bidder1', 'medianet']); + expect(noBidLog.mtype).to.have.ordered.members([banner, banner, banner, banner]); + expect(noBidLog.status).to.have.ordered.members(['1', '2', '2', '2']); + expect(noBidLog.size).to.have.ordered.members(['', '', '', '']); + expect(noBidLog.szs).to.have.ordered.members(['300x100|300x250', '300x100', '300x250', '300x250|300x100']); + }); + + it('AP log should fire only once', function() { + performStandardAuctionWithNoBid(); + events.emit(SET_TARGETING, MOCK.NO_BID_SET_TARGETING); + const logs = medianetAnalytics.getlogsQueue().map((log) => getQueryData(log, true)); + expect(logs.length).to.equal(1); + expect(logs[0].lgtp).to.equal('APPR'); + }); + it('should have winner log in standard auction', function() { medianetAnalytics.clearlogsQueue(); performStandardAuctionWithWinner(); From 4281953912f7da1f84a758c59a2a479270f7d329 Mon Sep 17 00:00:00 2001 From: rcheptanariu <35690143+rcheptanariu@users.noreply.github.com> Date: Thu, 23 Sep 2021 15:54:15 +0300 Subject: [PATCH 05/84] Invibes Bid Adapter : multi request support (#7398) * Invibes Bid Adapter - support for meta taxonomy * InvibesBidAdapter - support for multi placement * InvibesBidAdapter - support for multiplacement - tests & fixes * InvibesBidAdapter - fix object typo * InvibesBidAdapter - incremented version --- modules/invibesBidAdapter.js | 58 ++++++++-- test/spec/modules/invibesBidAdapter_spec.js | 116 +++++++++++++++++++- 2 files changed, 160 insertions(+), 14 deletions(-) diff --git a/modules/invibesBidAdapter.js b/modules/invibesBidAdapter.js index 18011359a6d..0441f712a2f 100644 --- a/modules/invibesBidAdapter.js +++ b/modules/invibesBidAdapter.js @@ -8,7 +8,7 @@ const CONSTANTS = { SYNC_ENDPOINT: 'https://k.r66net.com/GetUserSync', TIME_TO_LIVE: 300, DEFAULT_CURRENCY: 'EUR', - PREBID_VERSION: 6, + PREBID_VERSION: 7, METHOD: 'GET', INVIBES_VENDOR_ID: 436, USERID_PROVIDERS: ['pubcid', 'pubProvidedId', 'uid2', 'zeotapIdPlus', 'id5id'], @@ -57,14 +57,11 @@ const topWin = getTopMostWindow(); let invibes = topWin.invibes = topWin.invibes || {}; invibes.purposes = invibes.purposes || [false, false, false, false, false, false, false, false, false, false]; invibes.legitimateInterests = invibes.legitimateInterests || [false, false, false, false, false, false, false, false, false, false]; +invibes.placementBids = invibes.placementBids || []; +invibes.pushedCids = invibes.pushedCids || {}; let _customUserSync; function isBidRequestValid(bid) { - if (invibes && typeof invibes.bidResponse === 'object') { - utils.logInfo('Invibes Adapter - Bid response already received. Invibes only responds to one bid request per user visit'); - return false; - } - if (typeof bid.params !== 'object') { return false; } @@ -117,6 +114,7 @@ function buildRequest(bidRequests, bidderRequest) { bidParamsJson: JSON.stringify(bidParamsJson), capCounts: getCappedCampaignsAsString(), + pcids: Object.keys(invibes.pushedCids).join(','), vId: invibes.visitId, width: topWin.innerWidth, @@ -170,16 +168,25 @@ function handleResponse(responseObj, bidRequests) { responseObj = responseObj.videoAdContentResult || responseObj; if (typeof invibes.bidResponse === 'object') { - utils.logInfo('Invibes Adapter - Bid response already received. Invibes only responds to one bid request per user visit'); - return []; + if (responseObj.MultipositionEnabled === true) { + invibes.bidResponse.AdPlacements = invibes.bidResponse.AdPlacements.concat(responseObj.AdPlacements); + } else { + utils.logInfo('Invibes Adapter - Bid response already received. Invibes only responds to one bid request per user visit'); + return []; + } + } else { + invibes.bidResponse = responseObj; } - invibes.bidResponse = responseObj; - const bidResponses = []; for (let i = 0; i < bidRequests.length; i++) { let bidRequest = bidRequests[i]; + if (invibes.placementBids.indexOf(bidRequest.params.placementId) > -1) { + utils.logInfo('Invibes Adapter - Placement was previously bid on ' + bidRequest.params.placementId); + continue; + } + let requestPlacement = null; if (responseObj.AdPlacements != null) { for (let j = 0; j < responseObj.AdPlacements.length; j++) { @@ -196,8 +203,9 @@ function handleResponse(responseObj, bidRequests) { } } - let bid = createBid(bidRequest, requestPlacement); + let bid = createBid(bidRequest, requestPlacement, responseObj.MultipositionEnabled); if (bid !== null) { + invibes.placementBids.push(bidRequest.params.placementId); bidResponses.push(bid); } } @@ -205,7 +213,7 @@ function handleResponse(responseObj, bidRequests) { return bidResponses; } -function createBid(bidRequest, requestPlacement) { +function createBid(bidRequest, requestPlacement, multipositionEnabled) { if (requestPlacement === null || requestPlacement.BidModel === null) { utils.logInfo('Invibes Adapter - Placement not configured for bidding ' + bidRequest.params.placementId); return null; @@ -225,6 +233,30 @@ function createBid(bidRequest, requestPlacement) { let ad = ads[0]; let size = getBiggerSize(bidRequest.sizes); + if (multipositionEnabled === true) { + if (Object.keys(invibes.pushedCids).length > 0) { + if (ad.Blcids != null && ad.Blcids.length > 0) { + let blacklistsPushedCids = Object.keys(invibes.pushedCids).some(function(pushedCid) { + return ad.Blcids.indexOf(parseInt(pushedCid)) > -1; + }); + + if (blacklistsPushedCids) { + utils.logInfo('Invibes Adapter - Ad blacklists pushed ids'); + return null; + } + } + + let isBlacklisted = Object.keys(invibes.pushedCids).some(function(pushedCid) { + return invibes.pushedCids[pushedCid].indexOf(ad.Cid) > -1; + }); + if (isBlacklisted) { + utils.logInfo('Invibes Adapter - Ad is blacklisted'); + return null; + } + } + } + + invibes.pushedCids[ad.Cid] = ad.Blcids || []; const now = Date.now(); utils.logInfo('Bid auction started at ' + bidModel.AuctionStartTime + ' . Invibes registered the bid at ' + now + ' ; bid request took a total of ' + (now - bidModel.AuctionStartTime) + ' ms.'); @@ -660,6 +692,8 @@ export function resetInvibes() { invibes.dom = undefined; invibes.bidResponse = undefined; invibes.domainOptions = undefined; + invibes.placementBids = []; + invibes.pushedCids = {}; } export function stubDomainOptions(persistence) { diff --git a/test/spec/modules/invibesBidAdapter_spec.js b/test/spec/modules/invibesBidAdapter_spec.js index ea3e1d6611b..8b92e0ee81b 100644 --- a/test/spec/modules/invibesBidAdapter_spec.js +++ b/test/spec/modules/invibesBidAdapter_spec.js @@ -8,6 +8,39 @@ describe('invibesBidAdapter:', function () { const SYNC_ENDPOINT = 'https://k.r66net.com/GetUserSync'; let bidRequests = [ + { + bidId: 'b1', + bidder: BIDDER_CODE, + bidderRequestId: 'r1', + params: { + placementId: PLACEMENT_ID + }, + adUnitCode: 'test-div', + auctionId: 'a1', + sizes: [ + [300, 250], + [400, 300], + [125, 125] + ], + transactionId: 't1' + }, { + bidId: 'b2', + bidder: BIDDER_CODE, + bidderRequestId: 'r2', + params: { + placementId: 'abcde' + }, + adUnitCode: 'test-div', + auctionId: 'a2', + sizes: [ + [300, 250], + [400, 300] + ], + transactionId: 't2' + } + ]; + + let bidRequestsWithUserId = [ { bidId: 'b1', bidder: BIDDER_CODE, @@ -104,7 +137,7 @@ describe('invibesBidAdapter:', function () { expect(spec.isBidRequestValid(invalidBid)).to.be.false; }); - it('returns false when bid response was previously received', function () { + it('returns true when bid response was previously received', function () { const validBid = { bidder: BIDDER_CODE, params: { @@ -113,7 +146,7 @@ describe('invibesBidAdapter:', function () { } top.window.invibes.bidResponse = {prop: 'prop'}; - expect(spec.isBidRequestValid(validBid)).to.be.false; + expect(spec.isBidRequestValid(validBid)).to.be.true; }); }); }); @@ -190,11 +223,22 @@ describe('invibesBidAdapter:', function () { expect(JSON.parse(request.data.bidParamsJson).placementIds).to.contain(bidRequests[1].params.placementId); }); + it('sends all Placement Ids and userId', function () { + const request = spec.buildRequests(bidRequestsWithUserId); + expect(JSON.parse(request.data.bidParamsJson).userId).to.exist; + }); + it('sends undefined lid when no cookie', function () { let request = spec.buildRequests(bidRequests); expect(request.data.lId).to.be.undefined; }); + it('sends pushed cids if they exist', function () { + top.window.invibes.pushedCids = { 981: [] }; + let request = spec.buildRequests(bidRequests); + expect(request.data.pcids).to.contain(981); + }); + it('sends lid when comes on cookie', function () { top.window.invibes.optIn = 1; top.window.invibes.purposes = [true, false, false, false, false, false, false, false, false, false]; @@ -738,6 +782,7 @@ describe('invibesBidAdapter:', function () { }]; let multiResponse = { + MultipositionEnabled: true, AdPlacements: [{ Ads: [{ BidPrice: 0.5, @@ -778,6 +823,26 @@ describe('invibesBidAdapter:', function () { } }; + var buildResponse = function(placementId, cid, blcids, creativeId) { + return { + MultipositionEnabled: true, + AdPlacements: [{ + Ads: [{ + BidPrice: 0.5, + VideoExposedId: creativeId, + Cid: cid, + Blcids: blcids + }], + BidModel: { + BidVersion: 1, + PlacementId: placementId, + AuctionStartTime: Date.now(), + CreativeHtml: '' + } + }] + }; + }; + context('when the response is not valid', function () { it('handles response with no bids requested', function () { let emptyResult = spec.interpretResponse({body: response}); @@ -856,6 +921,53 @@ describe('invibesBidAdapter:', function () { expect(result[0].meta.advertiserDomains).to.contain('theadvertiser_2.com'); }); }); + + context('in multiposition context, with conflicting ads', function() { + it('registers the second ad when no conflict', function() { + var firstResponse = buildResponse('12345', 1, [1], 123); + var secondResponse = buildResponse('abcde', 2, [2], 456); + + var firstResult = spec.interpretResponse({body: firstResponse}, {bidRequests}); + var secondResult = spec.interpretResponse({body: secondResponse}, {bidRequests}); + expect(secondResult[0].creativeId).to.equal(456); + }); + + it('registers the second ad when no conflict - empty arrays', function() { + var firstResponse = buildResponse('12345', 1, [], 123); + var secondResponse = buildResponse('abcde', 2, [], 456); + + var firstResult = spec.interpretResponse({body: firstResponse}, {bidRequests}); + var secondResult = spec.interpretResponse({body: secondResponse}, {bidRequests}); + expect(secondResult[0].creativeId).to.equal(456); + }); + + it('doesnt register the second ad when it is blacklisted by the first', function() { + var firstResponse = buildResponse('12345', 1, [2], 123); + var secondResponse = buildResponse('abcde', 2, [], 456); + + var firstResult = spec.interpretResponse({body: firstResponse}, {bidRequests}); + var secondResult = spec.interpretResponse({body: secondResponse}, {bidRequests}); + expect(secondResult).to.be.empty; + }); + + it('doesnt register the second ad when it is blacklisting the first', function() { + var firstResponse = buildResponse('12345', 1, [], 123); + var secondResponse = buildResponse('abcde', 2, [1], 456); + + var firstResult = spec.interpretResponse({body: firstResponse}, {bidRequests}); + var secondResult = spec.interpretResponse({body: secondResponse}, {bidRequests}); + expect(secondResult).to.be.empty; + }); + + it('doesnt register the second ad when it has same ids as the first', function() { + var firstResponse = buildResponse('12345', 1, [1], 123); + var secondResponse = buildResponse('abcde', 1, [1], 456); + + var firstResult = spec.interpretResponse({body: firstResponse}, {bidRequests}); + var secondResult = spec.interpretResponse({body: secondResponse}, {bidRequests}); + expect(secondResult).to.be.empty; + }); + }); }); describe('getUserSyncs', function () { From 7b76219e767566310f671ecbe248573f6bf7a685 Mon Sep 17 00:00:00 2001 From: nllerandi3lift <75995508+nllerandi3lift@users.noreply.github.com> Date: Thu, 23 Sep 2021 09:57:10 -0400 Subject: [PATCH 06/84] Triplelift Bid Adapter: Increase Instream TTL (#7455) * removes duplicate eids from POST call * additional tests * pubcid support * Bump elliptic from 6.5.3 to 6.5.4 Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.3 to 6.5.4. - [Release notes](https://github.com/indutny/elliptic/releases) - [Commits](https://github.com/indutny/elliptic/compare/v6.5.3...v6.5.4) Signed-off-by: dependabot[bot] * Revert "Bump elliptic from 6.5.3 to 6.5.4" * increases instream TTL Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Dan Goldin Co-authored-by: Dan Goldin --- modules/tripleliftBidAdapter.js | 5 ++++- test/spec/modules/tripleliftBidAdapter_spec.js | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/tripleliftBidAdapter.js b/modules/tripleliftBidAdapter.js index e8d248eea03..2dc0b069a3c 100644 --- a/modules/tripleliftBidAdapter.js +++ b/modules/tripleliftBidAdapter.js @@ -6,6 +6,8 @@ import { config } from '../src/config.js'; const GVLID = 28; const BIDDER_CODE = 'triplelift'; const STR_ENDPOINT = 'https://tlx.3lift.com/header/auction?'; +const BANNER_TIME_TO_LIVE = 300; +const INSTREAM_TIME_TO_LIVE = 3600; let gdprApplies = true; let consentString = null; @@ -311,7 +313,7 @@ function _buildResponseObject(bidderRequest, bid) { creativeId: creativeId, dealId: dealId, currency: 'USD', - ttl: 300, + ttl: BANNER_TIME_TO_LIVE, tl_source: bid.tl_source, meta: {} }; @@ -319,6 +321,7 @@ function _buildResponseObject(bidderRequest, bid) { if (_isInstreamBidRequest(breq)) { bidResponse.vastXml = bid.ad; bidResponse.mediaType = 'video'; + bidResponse.ttl = INSTREAM_TIME_TO_LIVE; }; if (bid.advertiser_name) { diff --git a/test/spec/modules/tripleliftBidAdapter_spec.js b/test/spec/modules/tripleliftBidAdapter_spec.js index 30377ec0a5d..d523976826e 100644 --- a/test/spec/modules/tripleliftBidAdapter_spec.js +++ b/test/spec/modules/tripleliftBidAdapter_spec.js @@ -809,6 +809,8 @@ describe('triplelift adapter', function () { expect(result).to.have.length(2); expect(Object.keys(result[0])).to.have.members(Object.keys(expectedResponse[0])); expect(Object.keys(result[1])).to.have.members(Object.keys(expectedResponse[1])); + expect(result[0].ttl).to.equal(300); + expect(result[1].ttl).to.equal(3600); }); it('should return multiple responses to support SRA', function () { From 5b07374c7e6aa38b64fee22716a44f82f5dca7b6 Mon Sep 17 00:00:00 2001 From: TheMediaGrid <44166371+TheMediaGrid@users.noreply.github.com> Date: Thu, 23 Sep 2021 18:10:58 +0300 Subject: [PATCH 07/84] TheMediaGridNM: use /hbjson endpoint (#7430) * Added TheMediaGridNM Bid Adapter * Updated required params for TheMediaGridNM Bid Adapter * Update TheMediGridNM Bid Adapter * Fix tests for TheMediaGridNM Bid Adapter * Fixes after review for TheMediaGridNM Bid Adapter * Add support of multi-format in TheMediaGrid Bid Adapter * Update sync url for grid and gridNM Bid Adapters * TheMediaGrid Bid Adapter: added keywords adUnit parameter * Update TheMediaGrid Bid Adapter to support keywords from config * Implement new request format for TheMediaGrid Bid Adapter * Fix jwpseg params for TheMediaGrid Bid Adapter * Update unit tests for The Media Grid Bid Adapter * Fix typo in TheMediaGrid Bid Adapter * Added test for jwTargeting in TheMediaGrid Bid Adapter * The new request format was made by default in TheMediaGrid Bid Adapter * Update userId format in ad request for TheMediaGrid Bid Adapter * Added bidFloor parameter for TheMediaGrid Bid Adapter * Fix for review TheMediaGrid Bid Adapter * Support floorModule in TheMediaGrid Bid Adapter * Fix empty bidfloor for TheMediaGrid Bid Adapter * Some change to restart autotests * Fix userIds format for TheMediaGrid Bid Adapter * Remove digitrust userId from TheMediaGrid Bid Adapter * Protocols was added in video section in ad request for TheMediaGrid Bid Adapter * TheMediaGrid: fix trouble with alias using * TheMediaGridNM: fix trouble with alias * TheMediaGrid Bid Adapter: added support of PBAdSlot module * TheMediaGrid Bid Adapter: fix typo * GridNM Bid Adapter: use absent in params data from mediaTypes * GridNM Bid Adapter: fix md file + add advertiserDomains support * TheMediaGrid and gridNM Bid Adapter: minor netRevenue fixes * gridNM Bid Adapter updates after review * TheMediaGrid Bid Adapter: fix keywords workflow * fix testing and kick off lgtm again * TheMediaGrid: added ext.bidder.grid.demandSource processing * TheMediaGrid: added user.id from fpd cookie * TheMediaGrid: control cookie setting via bidder config * TheMediaGrid: use localStorage instead cookie * TheMediaGridNM Bid Adapter: update adapter to use /hbjson endpoint * TheMediaGridNM: fix unnecessary conditions Co-authored-by: Chris Huie --- modules/gridNMBidAdapter.js | 240 +++++++++++++++++---- test/spec/modules/gridNMBidAdapter_spec.js | 127 +++++++---- 2 files changed, 276 insertions(+), 91 deletions(-) diff --git a/modules/gridNMBidAdapter.js b/modules/gridNMBidAdapter.js index 4ab8464b115..66a244e1607 100644 --- a/modules/gridNMBidAdapter.js +++ b/modules/gridNMBidAdapter.js @@ -1,10 +1,11 @@ import * as utils from '../src/utils.js'; -import {registerBidder} from '../src/adapters/bidderFactory.js'; +import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; import { VIDEO } from '../src/mediaTypes.js'; +import { config } from '../src/config.js'; const BIDDER_CODE = 'gridNM'; -const ENDPOINT_URL = 'https://grid.bidswitch.net/hbnm'; +const ENDPOINT_URL = 'https://grid.bidswitch.net/hbjson'; const SYNC_URL = 'https://x.bidswitch.net/sync?ssp=themediagrid'; const TIME_TO_LIVE = 360; const RENDERER_URL = 'https://acdn.adnxs.com/video/outstream/ANOutstreamVideo.js'; @@ -64,62 +65,146 @@ export const spec = { buildRequests: function(validBidRequests, bidderRequest) { const bids = validBidRequests || []; const requests = []; + let { bidderRequestId, auctionId, gdprConsent, uspConsent, timeout, refererInfo } = bidderRequest || {}; + + const referer = refererInfo ? encodeURIComponent(refererInfo.referer) : ''; bids.forEach(bid => { - const { params, bidderRequestId, sizes } = bid; - const payload = { - sizes: utils.parseSizesInput(sizes).join(','), - r: bidderRequestId, - wrapperType: 'Prebid_js', - wrapperVersion: '$prebid.version$' - }; + let user; + let userExt; - if (bidderRequest) { - if (bidderRequest.refererInfo && bidderRequest.refererInfo.referer) { - payload.u = bidderRequest.refererInfo.referer; - } - if (bidderRequest.timeout) { - payload.wtimeout = bidderRequest.timeout; - } - if (bidderRequest.gdprConsent) { - if (bidderRequest.gdprConsent.consentString) { - payload.gdpr_consent = bidderRequest.gdprConsent.consentString; - } - payload.gdpr_applies = - (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') - ? Number(bidderRequest.gdprConsent.gdprApplies) : 1; + const schain = bid.schain; + const userIdAsEids = bid.userIdAsEids; + + if (!bidderRequestId) { + bidderRequestId = bid.bidderRequestId; + } + if (!auctionId) { + auctionId = bid.auctionId; + } + const { + params: { floorcpm, pubdata, source, secid, pubid, content, video }, + mediaTypes, bidId, adUnitCode, rtd, ortb2Imp, sizes + } = bid; + + const bidFloor = _getFloor(mediaTypes || {}, bid, utils.isNumber(floorcpm) && floorcpm); + const jwTargeting = rtd && rtd.jwplayer && rtd.jwplayer.targeting; + const jwpseg = (pubdata && pubdata.jwpseg) || (jwTargeting && jwTargeting.segments); + + const siteContent = content || (jwTargeting && jwTargeting.content); + + const impObj = { + id: bidId.toString(), + tagid: secid.toString(), + video: createVideoForImp(video, sizes, mediaTypes && mediaTypes.video), + ext: { + divid: adUnitCode.toString() } - if (bidderRequest.uspConsent) { - payload.us_privacy = bidderRequest.uspConsent; + }; + + if (ortb2Imp && ortb2Imp.ext && ortb2Imp.ext.data) { + impObj.ext.data = ortb2Imp.ext.data; + if (impObj.ext.data.adserver && impObj.ext.data.adserver.adslot) { + impObj.ext.gpid = impObj.ext.data.adserver.adslot.toString(); + } else { + impObj.ext.gpid = ortb2Imp.ext.data.pbadslot && ortb2Imp.ext.data.pbadslot.toString(); } } - const video = utils.deepAccess(bid, 'mediaTypes.video') || {}; - const paramsVideo = Object.assign({}, params.video); - VIDEO_KEYS.forEach((key) => { - if (!(key in paramsVideo) && key in video) { - paramsVideo[key] = video[key]; + if (bidFloor) { + impObj.bidfloor = bidFloor; + } + + const imp = [impObj]; + + const reqSource = { + tid: auctionId && auctionId.toString(), + ext: { + wrapper: 'Prebid_js', + wrapper_version: '$prebid.version$' } - }); + }; + + if (schain) { + reqSource.ext.schain = schain; + } + + const bidderTimeout = config.getConfig('bidderTimeout') || timeout; + const tmax = timeout ? Math.min(bidderTimeout, timeout) : bidderTimeout; + + const request = { + id: bidderRequestId && bidderRequestId.toString(), + site: { + page: referer, + publisher: { + id: pubid, + }, + }, + source: reqSource, + tmax, + imp, + }; + + if (siteContent) { + request.site.content = siteContent; + } + + if (jwpseg && jwpseg.length) { + user = { + data: [{ + name: 'iow_labs_pub_data', + segment: jwpseg.map((seg) => { + return {name: 'jwpseg', value: seg}; + }) + }] + }; + } + + if (gdprConsent && gdprConsent.consentString) { + userExt = { consent: gdprConsent.consentString }; + } + + if (userIdAsEids && userIdAsEids.length) { + userExt = userExt || {}; + userExt.eids = [...userIdAsEids]; + } + + if (userExt && Object.keys(userExt).length) { + user = user || {}; + user.ext = userExt; + } - if (!paramsVideo.size && video.playerSize && video.playerSize.length === 2) { - paramsVideo.size = video.playerSize.join('x'); + if (user) { + request.user = user; } - if (!('mind' in paramsVideo) && 'minduration' in video) { - paramsVideo.mind = video.minduration; + if (gdprConsent && gdprConsent.gdprApplies) { + request.regs = { + ext: { + gdpr: gdprConsent.gdprApplies ? 1 : 0 + } + } } - if (!('maxd' in paramsVideo) && 'maxduration' in video) { - paramsVideo.maxd = video.maxduration; + + if (uspConsent) { + if (!request.regs) { + request.regs = { ext: {} }; + } + request.regs.ext.us_privacy = uspConsent; } - const paramsToSend = Object.assign({}, params, {video: paramsVideo}); + if (config.getConfig('coppa') === true) { + if (!request.regs) { + request.regs = {}; + } + request.regs.coppa = 1; + } requests.push({ method: 'POST', - url: ENDPOINT_URL + '?' + utils.parseQueryStringParameters(payload).replace(/\&$/, ''), + url: ENDPOINT_URL + '?no_mapping=1&sp=' + source, bid: bid, - data: paramsToSend // content + data: request }); }); @@ -151,11 +236,6 @@ export const spec = { else if (serverBid.content_type !== 'video') errorMessage = LOG_ERROR_MESS.wrongContentType + serverBid.content_type; if (!errorMessage) { const bid = bidRequest.bid; - if (!serverBid.w || !serverBid.h) { - const size = utils.parseSizesInput(bid.sizes)[0].split('x'); - serverBid.w = size[0]; - serverBid.h = size[1]; - } const bidResponse = { requestId: bid.bidId, cpm: serverBid.price, @@ -176,6 +256,10 @@ export const spec = { } }; + if (serverBid.nurl) { + bidResponse.vastUrl = serverBid.nurl; + } + if (!bid.renderer && (!bid.mediaTypes || !bid.mediaTypes.video || bid.mediaTypes.video.context === 'outstream')) { bidResponse.renderer = createRenderer(bidResponse, { id: bid.bidId, @@ -213,6 +297,33 @@ export const spec = { } }; +/** + * Gets bidfloor + * @param {Object} mediaTypes + * @param {Object} bid + * @param {Number} floor + * @returns {Number} floor + */ +function _getFloor (mediaTypes, bid, floor) { + const curMediaType = mediaTypes.video ? 'video' : 'banner'; + + if (typeof bid.getFloor === 'function') { + const floorInfo = bid.getFloor({ + currency: 'USD', + mediaType: curMediaType, + size: bid.sizes.map(([w, h]) => ({w, h})) + }); + + if (typeof floorInfo === 'object' && + floorInfo.currency === 'USD' && + !isNaN(parseFloat(floorInfo.floor))) { + floor = Math.max(floor, parseFloat(floorInfo.floor)); + } + } + + return floor; +} + function _getBidFromResponse(respItem) { if (!respItem) { utils.logError(LOG_ERROR_MESS.emptySeatbid); @@ -249,6 +360,45 @@ function createRenderer (bid, rendererParams) { return renderer; } +function createVideoForImp({ mind, maxd, size, ...paramsVideo }, bidSizes, bidVideo = {}) { + VIDEO_KEYS.forEach((key) => { + if (!(key in paramsVideo) && key in bidVideo) { + paramsVideo[key] = bidVideo[key]; + } + }); + + if (size && utils.isStr(size)) { + const sizeArray = size.split('x'); + if (sizeArray.length === 2 && parseInt(sizeArray[0]) && parseInt(sizeArray[1])) { + paramsVideo.w = parseInt(sizeArray[0]); + paramsVideo.h = parseInt(sizeArray[1]); + } + } + + if (!paramsVideo.w || !paramsVideo.h) { + const playerSizes = bidVideo.playerSize && bidVideo.playerSize.length === 2 ? bidVideo.playerSize : bidSizes; + if (playerSizes) { + const playerSize = playerSizes[0]; + if (playerSize) { + Object.assign(paramsVideo, utils.parseGPTSingleSizeArrayToRtbSize(playerSize)); + } + } + } + + const durationRangeSec = bidVideo.durationRangeSec || []; + const minDur = mind || durationRangeSec[0] || bidVideo.minduration; + const maxDur = maxd || durationRangeSec[1] || bidVideo.maxduration; + + if (minDur) { + paramsVideo.minduration = minDur; + } + if (maxDur) { + paramsVideo.maxduration = maxDur; + } + + return paramsVideo; +} + export function resetUserSync() { hasSynced = false; } diff --git a/test/spec/modules/gridNMBidAdapter_spec.js b/test/spec/modules/gridNMBidAdapter_spec.js index 6d3a607c0c5..baff5862fca 100644 --- a/test/spec/modules/gridNMBidAdapter_spec.js +++ b/test/spec/modules/gridNMBidAdapter_spec.js @@ -180,13 +180,19 @@ describe('TheMediaGridNM Adapter', function () { }); return res; } - const bidderRequest = {refererInfo: {referer: 'https://example.com'}}; - const referrer = bidderRequest.refererInfo.referer; + const bidderRequest = { + bidderRequestId: '22edbae2733bf6', + auctionId: '1d1a030790a475', + timeout: 3000, + refererInfo: { referer: 'https://example.com' } + }; + const referrer = encodeURIComponent(bidderRequest.refererInfo.referer); let bidRequests = [ { 'bidder': 'gridNM', 'params': { 'source': 'jwp', + 'floorcpm': 2, 'secid': '11', 'pubid': '22', 'video': { @@ -226,12 +232,36 @@ describe('TheMediaGridNM Adapter', function () { requests.forEach((req, i) => { expect(req.url).to.be.an('string'); const payload = parseRequestUrl(req.url); - expect(payload).to.have.property('u', referrer); - expect(payload).to.have.property('r', '22edbae2733bf6'); - expect(payload).to.have.property('wrapperType', 'Prebid_js'); - expect(payload).to.have.property('wrapperVersion', '$prebid.version$'); - expect(payload).to.have.property('sizes', requestsSizes[i]); - expect(req.data).to.deep.equal(bidRequests[i].params); + expect(payload).to.have.property('no_mapping', '1'); + expect(payload).to.have.property('sp', 'jwp'); + + const sizes = { w: bidRequests[i].sizes[0][0], h: bidRequests[i].sizes[0][1] }; + const impObj = { + 'id': bidRequests[i].bidId, + 'tagid': bidRequests[i].params.secid, + 'ext': {'divid': bidRequests[i].adUnitCode}, + 'video': Object.assign(sizes, bidRequests[i].params.video) + }; + + if (bidRequests[i].params.floorcpm) { + impObj.bidfloor = bidRequests[i].params.floorcpm; + } + + expect(req.data).to.deep.equal({ + 'id': bidderRequest.bidderRequestId, + 'site': { + 'page': referrer, + 'publisher': { + 'id': bidRequests[i].params.pubid + } + }, + 'tmax': bidderRequest.timeout, + 'source': { + 'tid': bidderRequest.auctionId, + 'ext': {'wrapper': 'Prebid_js', 'wrapper_version': '$prebid.version$'} + }, + 'imp': [impObj] + }); }); }); @@ -242,63 +272,68 @@ describe('TheMediaGridNM Adapter', function () { minduration: 10, maxduration: 100, protocols: [1, 3, 4], - playerSize: [300, 250] + playerSize: [[300, 250]] } }; const bidRequest = Object.assign({ mediaTypes }, bidRequests[0]); const req = spec.buildRequests([bidRequest], bidderRequest)[0]; const expectedVideo = { 'skipafter': 10, - 'mind': 10, - 'maxd': 100, + 'minduration': 10, + 'maxduration': 100, 'mimes': ['video/mp4', 'video/x-ms-wmv'], 'protocols': [1, 2, 3, 4, 5, 6], - 'size': '300x250' + 'w': 300, + 'h': 250 }; - const expectedParams = Object.assign({}, bidRequest.params); - expectedParams.video = Object.assign(expectedParams.video, expectedVideo); expect(req.url).to.be.an('string'); const payload = parseRequestUrl(req.url); - expect(payload).to.have.property('u', referrer); - expect(payload).to.have.property('r', '22edbae2733bf6'); - expect(payload).to.have.property('wrapperType', 'Prebid_js'); - expect(payload).to.have.property('wrapperVersion', '$prebid.version$'); - expect(payload).to.have.property('sizes', '300x250,300x600'); - expect(req.data).to.deep.equal(expectedParams); + expect(payload).to.have.property('no_mapping', '1'); + expect(payload).to.have.property('sp', 'jwp'); + expect(req.data).to.deep.equal({ + 'id': bidderRequest.bidderRequestId, + 'site': { + 'page': referrer, + 'publisher': { + 'id': bidRequest.params.pubid + } + }, + 'tmax': bidderRequest.timeout, + 'source': { + 'tid': bidderRequest.auctionId, + 'ext': {'wrapper': 'Prebid_js', 'wrapper_version': '$prebid.version$'} + }, + 'imp': [{ + 'id': bidRequest.bidId, + 'bidfloor': bidRequest.params.floorcpm, + 'tagid': bidRequest.params.secid, + 'ext': {'divid': bidRequest.adUnitCode}, + 'video': expectedVideo + }] + }); }); it('if gdprConsent is present payload must have gdpr params', function () { - const [request] = spec.buildRequests([bidRequests[0]], {gdprConsent: {consentString: 'AAA', gdprApplies: true}, refererInfo: bidderRequest.refererInfo}); - expect(request.url).to.be.an('string'); - const payload = parseRequestUrl(request.url); - expect(payload).to.have.property('u', referrer); - expect(payload).to.have.property('gdpr_consent', 'AAA'); - expect(payload).to.have.property('gdpr_applies', '1'); - }); - - it('if gdprApplies is false gdpr_applies must be 0', function () { - const [request] = spec.buildRequests([bidRequests[0]], {gdprConsent: {consentString: 'AAA', gdprApplies: false}}); - expect(request.url).to.be.an('string'); - const payload = parseRequestUrl(request.url); - expect(payload).to.have.property('gdpr_consent', 'AAA'); - expect(payload).to.have.property('gdpr_applies', '0'); - }); - - it('if gdprApplies is undefined gdpr_applies must be 1', function () { - const [request] = spec.buildRequests([bidRequests[0]], {gdprConsent: {consentString: 'AAA'}}); - expect(request.url).to.be.an('string'); - const payload = parseRequestUrl(request.url); - expect(payload).to.have.property('gdpr_consent', 'AAA'); - expect(payload).to.have.property('gdpr_applies', '1'); + const gdprBidderRequest = Object.assign({gdprConsent: {consentString: 'AAA', gdprApplies: true}}, bidderRequest); + const request = spec.buildRequests([bidRequests[0]], gdprBidderRequest)[0]; + const payload = request.data; + expect(request).to.have.property('data'); + expect(payload).to.have.property('user'); + expect(payload.user).to.have.property('ext'); + expect(payload.user.ext).to.have.property('consent', 'AAA'); + expect(payload).to.have.property('regs'); + expect(payload.regs).to.have.property('ext'); + expect(payload.regs.ext).to.have.property('gdpr', 1); }); it('if usPrivacy is present payload must have us_privacy param', function () { const bidderRequestWithUSP = Object.assign({uspConsent: '1YNN'}, bidderRequest); - const [request] = spec.buildRequests([bidRequests[0]], bidderRequestWithUSP); - expect(request.url).to.be.an('string'); - const payload = parseRequestUrl(request.url); - expect(payload).to.have.property('us_privacy', '1YNN'); + const request = spec.buildRequests([bidRequests[0]], bidderRequestWithUSP)[0]; + const payload = request.data; + expect(payload).to.have.property('regs'); + expect(payload.regs).to.have.property('ext'); + expect(payload.regs.ext).to.have.property('us_privacy', '1YNN'); }); }); From a5482376282b2376b7eb1074a87de8039bc27e42 Mon Sep 17 00:00:00 2001 From: Michael Burns Date: Thu, 23 Sep 2021 11:12:37 -0400 Subject: [PATCH 08/84] Fix inf loop (#7460) --- modules/ixBidAdapter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ixBidAdapter.js b/modules/ixBidAdapter.js index 8f821e87911..4ff84e7c104 100644 --- a/modules/ixBidAdapter.js +++ b/modules/ixBidAdapter.js @@ -638,7 +638,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { let currentImpressionSize = encodeURIComponent(JSON.stringify({ impressionObjects })).length; - while (currentImpressionSize > remainingRequestSize) { + while (impressionObjects.length && currentImpressionSize > remainingRequestSize) { wasAdUnitImpressionsTrimmed = true; impressionObjects.pop(); currentImpressionSize = encodeURIComponent(JSON.stringify({ impressionObjects })).length; From 6ab27bd09cf8a873c26498ec6b46282178edab1f Mon Sep 17 00:00:00 2001 From: Tiago Peczenyj Date: Thu, 23 Sep 2021 17:30:49 +0200 Subject: [PATCH 09/84] update .submodules.json to include weborama rtd (#7461) update .submodules.json to include weborama rtd submodule --- modules/.submodules.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/.submodules.json b/modules/.submodules.json index 3a3b94ea469..87b05dca33d 100644 --- a/modules/.submodules.json +++ b/modules/.submodules.json @@ -51,7 +51,8 @@ "permutiveRtdProvider", "reconciliationRtdProvider", "sirdataRtdProvider", - "timeoutRtdProvider" + "timeoutRtdProvider", + "weboramaRtdProvider" ], "fpdModule": [ "enrichmentFpdModule", From b2577b7afca04a06d9b8e4d3e83fb0aa602e5ef1 Mon Sep 17 00:00:00 2001 From: Catalin Ciocov Date: Thu, 23 Sep 2021 20:40:44 +0300 Subject: [PATCH 10/84] Inskin Bid Adapter: override schain with publisher id (#7444) * Set publisher ID as schain id * Updated Inskin markdown file --- modules/inskinBidAdapter.js | 12 ++++++++++++ modules/inskinBidAdapter.md | 9 +++++---- test/spec/modules/inskinBidAdapter_spec.js | 11 ++++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/modules/inskinBidAdapter.js b/modules/inskinBidAdapter.js index 5173f1dca63..8f2e35a41e0 100644 --- a/modules/inskinBidAdapter.js +++ b/modules/inskinBidAdapter.js @@ -55,6 +55,18 @@ export const spec = { parallel: true }, validBidRequests[0].params); + if (data.publisherId) { + data.rtb = { + schain: { + ext: { + sid: String(data.publisherId) + } + } + }; + + delete data.publisherId; + } + data.keywords = data.keywords || []; const restrictions = []; diff --git a/modules/inskinBidAdapter.md b/modules/inskinBidAdapter.md index 2284124dc98..2cb19f9a0e0 100644 --- a/modules/inskinBidAdapter.md +++ b/modules/inskinBidAdapter.md @@ -1,14 +1,14 @@ # Overview -Module Name: InSkin Bid Adapter +Module Name: Inskin Bid Adapter Module Type: Bid Adapter -Maintainer: jgrimes@adzerk.com +Maintainer: tech@inskinmedia.com # Description -Connects to InSkin Media for receiving bids from configured demand sources. +Connects to Inskin Media for receiving bids from configured demand sources. # Test Parameters ```javascript @@ -21,7 +21,8 @@ Connects to InSkin Media for receiving bids from configured demand sources. bidder: 'inskin', params: { networkId: '9874', - siteId: '983808' + siteId: '983808', + publisherId: '123456' } } ] diff --git a/test/spec/modules/inskinBidAdapter_spec.js b/test/spec/modules/inskinBidAdapter_spec.js index 151cbce7692..3d0ec82fca5 100644 --- a/test/spec/modules/inskinBidAdapter_spec.js +++ b/test/spec/modules/inskinBidAdapter_spec.js @@ -12,7 +12,8 @@ const REQUEST = { 'bidder': 'inskin', 'params': { 'networkId': 9874, - 'siteId': 730181 + 'siteId': 730181, + 'publisherId': 123456 }, 'placementCode': 'div-gpt-ad-1487778092495-0', 'sizes': [ @@ -374,4 +375,12 @@ describe('InSkin BidAdapter', function () { expect(opts.length).to.equal(3); }); }); + describe('supply chain id', function () { + it('should use publisherId as sid', function () { + const request = spec.buildRequests(REQUEST.bidRequest, bidderRequest); + const payload = JSON.parse(request.data); + + expect(payload.rtb.schain.ext.sid).to.equal('123456'); + }); + }); }); From 795f3a16e50275f25474d0a68d837bc136cee39f Mon Sep 17 00:00:00 2001 From: Jason Snellbaker Date: Thu, 23 Sep 2021 14:07:57 -0400 Subject: [PATCH 11/84] Prebid 5.15.0 Release --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b6a861f60d4..3c719773479 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prebid.js", - "version": "5.15.0-pre", + "version": "5.15.0", "description": "Header Bidding Management Library", "main": "src/prebid.js", "scripts": { From f607450696f22ddce07b6a8bd28bf97e806bbfcf Mon Sep 17 00:00:00 2001 From: Jason Snellbaker Date: Thu, 23 Sep 2021 14:25:37 -0400 Subject: [PATCH 12/84] increment pre version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3c719773479..e254410e5fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prebid.js", - "version": "5.15.0", + "version": "5.16.0-pre", "description": "Header Bidding Management Library", "main": "src/prebid.js", "scripts": { From a0d085ea51b945fe3099daf9e015ee31f4ffb1bf Mon Sep 17 00:00:00 2001 From: Paul Yang Date: Thu, 23 Sep 2021 14:13:03 -0700 Subject: [PATCH 13/84] PublinkId - validate hash and fix decode (#7439) --- modules/conversantBidAdapter.js | 1 + modules/publinkIdSystem.js | 17 +++++++++++--- test/spec/modules/publinkIdSystem_spec.js | 27 ++++++++++++++++------- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/modules/conversantBidAdapter.js b/modules/conversantBidAdapter.js index a1ca094273b..5e05499a18e 100644 --- a/modules/conversantBidAdapter.js +++ b/modules/conversantBidAdapter.js @@ -373,6 +373,7 @@ function collectEids(bidRequests) { if (utils.isArray(request.userIdAsEids) && request.userIdAsEids.length > 0) { // later following white-list can be converted to block-list if needed const requiredSourceValues = { + 'epsilon.com': 1, 'adserver.org': 1, 'liveramp.com': 1, 'criteo.com': 1, diff --git a/modules/publinkIdSystem.js b/modules/publinkIdSystem.js index 5e549732097..ca6ca9cf8d8 100644 --- a/modules/publinkIdSystem.js +++ b/modules/publinkIdSystem.js @@ -18,6 +18,10 @@ const PUBLINK_S2S_COOKIE = '_publink_srv'; export const storage = getStorageManager(GVLID); +function isHex(s) { + return (typeof s === 'string' && /^[A-F0-9]+$/i.test(s)); +} + function publinkIdUrl(params, consentData) { let url = utils.parseUrl('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink'); url.search = { @@ -49,8 +53,13 @@ function makeCallback(config = {}, consentData) { } } }; + if (config.params && config.params.e) { - ajax(publinkIdUrl(config.params, consentData), handleResponse, undefined, options); + if (isHex(config.params.e)) { + ajax(publinkIdUrl(config.params, consentData), handleResponse, undefined, options); + } else { + utils.logError('params.e must be a hex string'); + } } }; } @@ -96,11 +105,11 @@ export const publinkIdSubmodule = { /** * decode the stored id value for passing to bid requests * @function - * @param {string} id encrypted userid + * @param {string} publinkId encrypted userid * @returns {{publinkId: string} | undefined} */ decode(publinkId) { - return {publink: publinkId}; + return {publinkId: publinkId}; }, /** @@ -108,6 +117,8 @@ export const publinkIdSubmodule = { * Use a publink cookie first if it is present, otherwise use prebids copy, if neither are available callout to get a new id * @function * @param {SubmoduleConfig} [config] Config object with params and storage properties + * @param {ConsentData|undefined} consentData GDPR consent + * @param {(Object|undefined)} storedId Previously cached id * @returns {IdResponse} */ getId: function(config, consentData, storedId) { diff --git a/test/spec/modules/publinkIdSystem_spec.js b/test/spec/modules/publinkIdSystem_spec.js index 2999fda5aa0..0680e02e3fa 100644 --- a/test/spec/modules/publinkIdSystem_spec.js +++ b/test/spec/modules/publinkIdSystem_spec.js @@ -10,7 +10,7 @@ describe('PublinkIdSystem', () => { describe('decode', () => { it('decode', () => { const result = publinkIdSubmodule.decode(TEST_COOKIE_VALUE); - expect(result).deep.equals({publink: TEST_COOKIE_VALUE}); + expect(result).deep.equals({publinkId: TEST_COOKIE_VALUE}); }); }); @@ -69,6 +69,7 @@ describe('PublinkIdSystem', () => { expect(result).to.exist; expect(result.callback).to.be.a('function'); }); + it('Use local copy', () => { const result = publinkIdSubmodule.getId({}, undefined, TEST_COOKIE_VALUE); expect(result).to.be.undefined; @@ -82,14 +83,14 @@ describe('PublinkIdSystem', () => { }); it('Fetch with consent data', () => { - const config = {storage: {type: 'cookie'}, params: {e: 'hashedemailvalue'}}; + const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7'}}; const consentData = {gdprApplies: 1, consentString: 'myconsentstring'}; let submoduleCallback = publinkIdSubmodule.getId(config, consentData).callback; submoduleCallback(callbackSpy); let request = server.requests[0]; request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=hashedemailvalue&mpn=Prebid.js&mpv=$prebid.version$&gdpr=1&gdpr_consent=myconsentstring'); + expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$&gdpr=1&gdpr_consent=myconsentstring'); request.respond(200, {}, JSON.stringify(serverResponse)); expect(callbackSpy.calledOnce).to.be.true; @@ -97,16 +98,26 @@ describe('PublinkIdSystem', () => { }); it('server doesnt respond', () => { - const config = {storage: {type: 'cookie'}, params: {e: 'hashedemailvalue'}}; + const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7'}}; let submoduleCallback = publinkIdSubmodule.getId(config).callback; submoduleCallback(callbackSpy); let request = server.requests[0]; request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=hashedemailvalue&mpn=Prebid.js&mpv=$prebid.version$'); + expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$'); request.respond(204, {}, JSON.stringify(serverResponse)); - expect(callbackSpy.calledOnce).to.be.false; + expect(callbackSpy.called).to.be.false; + }); + + it('reject plain email address', () => { + const config = {storage: {type: 'cookie'}, params: {e: 'tester@test.com'}}; + const consentData = {gdprApplies: 1, consentString: 'myconsentstring'}; + let submoduleCallback = publinkIdSubmodule.getId(config, consentData).callback; + submoduleCallback(callbackSpy); + + expect(server.requests).to.have.lengthOf(0); + expect(callbackSpy.called).to.be.false; }); }); @@ -122,13 +133,13 @@ describe('PublinkIdSystem', () => { }); it('Fetch with usprivacy data', () => { - const config = {storage: {type: 'cookie'}, params: {e: 'hashedemailvalue'}}; + const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7'}}; let submoduleCallback = publinkIdSubmodule.getId(config).callback; submoduleCallback(callbackSpy); let request = server.requests[0]; request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=hashedemailvalue&mpn=Prebid.js&mpv=$prebid.version$&us_privacy=1YNN'); + expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$&us_privacy=1YNN'); request.respond(200, {}, JSON.stringify(serverResponse)); expect(callbackSpy.calledOnce).to.be.true; From 8eb0f77c194a8a1ae3b00133d1a6617a35adc8f2 Mon Sep 17 00:00:00 2001 From: Sasan Farrokh Date: Fri, 24 Sep 2021 16:55:36 +0330 Subject: [PATCH 14/84] Vidoomy Bid Adapter: bugfix for cookie sync with pixel fires (#7407) * fix: vidoomy adapter, cookie sync with pixel fires * fix: revert package-lock.json * fix: switch to xhr * fix: remove index.html Co-authored-by: Sasan Farrokh --- modules/vidoomyBidAdapter.js | 101 ++++++++++++++++++++++++++++++----- 1 file changed, 88 insertions(+), 13 deletions(-) diff --git a/modules/vidoomyBidAdapter.js b/modules/vidoomyBidAdapter.js index b579de8618b..78c19a38b6a 100644 --- a/modules/vidoomyBidAdapter.js +++ b/modules/vidoomyBidAdapter.js @@ -8,6 +8,9 @@ import { INSTREAM, OUTSTREAM } from '../src/video.js'; const ENDPOINT = `https://d.vidoomy.com/api/rtbserver/prebid/`; const BIDDER_CODE = 'vidoomy'; const GVLID = 380; + +const COOKIE_SYNC_JSON = 'https://vpaid.vidoomy.com/sync/urls.json'; + const isBidRequestValid = bid => { if (!bid.params) { utils.logError(BIDDER_CODE + ': bid.params should be non-empty'); @@ -58,17 +61,9 @@ const buildRequests = (validBidRequests, bidderRequest) => { adType = VIDEO; } - let host = ''; - try { - host = bidderRequest.refererInfo.referer.split('#')[0].replace(/^(https\:\/\/|http\:\/\/)|(\/)$/g, '').split('/')[0]; - } catch (eBidRequest) { - try { - host = window.location.href.replace(/^(https\:\/\/|http\:\/\/)|(\/)$/g, '').split('/')[0]; - } catch (eLocationHref) { - host = window.location.href; - } - } - const hostname = host.split(':')[0]; + const aElement = document.createElement('a'); + aElement.href = (bidderRequest.refererInfo && bidderRequest.refererInfo.referer) || top.location.href; + const hostname = aElement.hostname const videoContext = utils.deepAccess(bid, 'mediaTypes.video.context'); @@ -83,8 +78,8 @@ const buildRequests = (validBidRequests, bidderRequest) => { queryParams.push(['dt', /Mobi/.test(navigator.userAgent) ? 2 : 1]); queryParams.push(['pid', bid.params.pid]); queryParams.push(['requestId', bid.bidId]); - queryParams.push(['d', hostname]); - queryParams.push(['sp', encodeURIComponent(bidderRequest.refererInfo.referer)]); + queryParams.push(['d', getDomainWithoutSubdomain(hostname)]); + queryParams.push(['sp', encodeURIComponent(aElement.href)]); if (bidderRequest.gdprConsent) { queryParams.push(['gdpr', bidderRequest.gdprConsent.gdprApplies]); queryParams.push(['gdprcs', bidderRequest.gdprConsent.consentString]); @@ -94,6 +89,19 @@ const buildRequests = (validBidRequests, bidderRequest) => { const rawQueryParams = queryParams.map(qp => qp.join('=')).join('&'); + const xhr = new XMLHttpRequest(); + xhr.open('GET', COOKIE_SYNC_JSON) + xhr.addEventListener('load', function () { + const macro = Macro({ + gpdr: bidderRequest.gdprConsent.gdprApplies, + gpdr_consent: bidderRequest.gdprConsent.consentString + }); + JSON.parse(this.responseText).filter(Boolean).forEach(url => { + firePixel(macro.replace(url)) + }) + }) + xhr.send() + const url = `${ENDPOINT}?${rawQueryParams}`; return { method: 'GET', @@ -198,3 +206,70 @@ export const spec = { }; registerBidder(spec); + +function firePixel(url) { + const img = document.createElement('img'); + img.width = 1; + img.height = 1; + img.src = url; + document.body.appendChild(img); + setTimeout(() => { + img.remove(); + }, 10000) +} + +function normalizeKey (x) { + return x.replace(/_/g, '').toLowerCase(); +} + +function Macro (obj) { + const macros = {}; + for (const key in obj) { + macros[normalizeKey(key)] = obj[key]; + } + + const set = (key, value) => { + macros[normalizeKey(key)] = typeof value === 'function' ? value : String(value); + }; + + return { + set, + setAll (obj) { + for (const key in obj) { + macros[normalizeKey(key)] = set(obj[key]); + } + }, + replace (string, extraMacros = {}) { + const allMacros = { + ...macros, + ...extraMacros, + }; + const regexes = [ + /{{\s*([a-zA-Z0-9_]+)\s*}}/g, + /\$\$\s*([a-zA-Z0-9_]+)\s*\$\$/g, + /\[\s*([a-zA-Z0-9_]+)\s*\]/g, + ]; + regexes.forEach(regex => { + string = string.replace(regex, (str, x) => { + x = normalizeKey(x); + let value = allMacros[x]; + value = typeof value === 'function' ? value(allMacros) : value; + return !value && value !== 0 ? '' : value; + }); + }); + return string; + }, + }; +} + +function getDomainWithoutSubdomain (hostname) { + const parts = hostname.split('.'); + const newParts = []; + for (let i = parts.length - 1; i >= 0; i--) { + newParts.push(parts[i]); + if (newParts.length !== 1 && parts[i].length > 3) { + break; + } + } + return newParts.reverse().join('.'); +} From d02fee2e3f4938542cafd71093a3c78d8e93984a Mon Sep 17 00:00:00 2001 From: Bill Newman Date: Fri, 24 Sep 2021 16:38:56 +0300 Subject: [PATCH 15/84] Colossus Adapter: add pbAdSlot support (#7464) * add video&native traffic colossus ssp * Native obj validation * Native obj validation #2 * Added size field in requests * fixed test * fix merge conflicts * move to 3.0 * move to 3.0 * fix IE11 new URL issue * fix IE11 new URL issue * fix IE11 new URL issue * https for 3.0 * add https test * add ccp and schain features * fix test * sync with upstream, fix conflicts * Update colossussspBidAdapter.js remove commented code * Update colossussspBidAdapter.js lint fix * identity extensions * identity extensions * fix * fix * fix * fix * fix * add tests for user ids * fix * fix * fix * fix * fix * fix * fix * add gdpr support * add gdpr support * id5id support * Update colossussspBidAdapter.js add bidfloor parameter * Update colossussspBidAdapter.js check bidfloor * Update colossussspBidAdapter.js * Update colossussspBidAdapter.js * Update colossussspBidAdapter.js * Update colossussspBidAdapter_spec.js * use floor module * Revert "use floor module" This reverts commit f0c5c248627567e669d8eed4f2bb9a26a857e2ad. * use floor module * update to 5v * fix * add uid2 and bidFloor support * fix * add pbadslot support Co-authored-by: Vladislav Isaiko Co-authored-by: Aiholkin Co-authored-by: Mykhailo Yaremchuk --- modules/colossussspBidAdapter.js | 4 ++++ .../modules/colossussspBidAdapter_spec.js | 20 +++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/modules/colossussspBidAdapter.js b/modules/colossussspBidAdapter.js index 52865b8085d..b000cefd1b2 100644 --- a/modules/colossussspBidAdapter.js +++ b/modules/colossussspBidAdapter.js @@ -106,6 +106,10 @@ export const spec = { if (bid.schain) { placement.schain = bid.schain; } + let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + if (gpid) { + placement.gpid = gpid; + } if (bid.userId) { getUserId(placement.eids, bid.userId.britepoolid, 'britepool.com'); getUserId(placement.eids, bid.userId.idl_env, 'identityLink'); diff --git a/test/spec/modules/colossussspBidAdapter_spec.js b/test/spec/modules/colossussspBidAdapter_spec.js index fa543f28fd1..0fe4d5b358e 100644 --- a/test/spec/modules/colossussspBidAdapter_spec.js +++ b/test/spec/modules/colossussspBidAdapter_spec.js @@ -1,5 +1,5 @@ -import {expect} from 'chai'; -import {spec} from '../../../modules/colossussspBidAdapter.js'; +import { expect } from 'chai'; +import { spec } from '../../../modules/colossussspBidAdapter.js'; describe('ColossussspAdapter', function () { let bid = { @@ -16,6 +16,13 @@ describe('ColossussspAdapter', function () { sizes: [[300, 250]] } }, + ortb2Imp: { + ext: { + data: { + pbadslot: '/19968336/prebid_cache_video_adunit' + } + } + }, transactionId: '3bb2f6da-87a6-4029-aeb0-bfe951372e62', schain: { ver: '1.0', @@ -71,7 +78,7 @@ describe('ColossussspAdapter', function () { it('Returns valid URL', function () { expect(serverRequest.url).to.equal('https://colossusssp.com/?c=o&m=multi'); }); - it('Should contain ccpa', function() { + it('Should contain ccpa', function () { expect(serverRequest.data.ccpa).to.be.an('string') }) @@ -88,13 +95,14 @@ describe('ColossussspAdapter', function () { let placements = data['placements']; for (let i = 0; i < placements.length; i++) { let placement = placements[i]; - expect(placement).to.have.all.keys('placementId', 'eids', 'bidId', 'traffic', 'sizes', 'schain', 'floor'); + expect(placement).to.have.all.keys('placementId', 'eids', 'bidId', 'traffic', 'sizes', 'schain', 'floor', 'gpid'); expect(placement.schain).to.be.an('object') expect(placement.placementId).to.be.a('number'); expect(placement.bidId).to.be.a('string'); expect(placement.traffic).to.be.a('string'); expect(placement.sizes).to.be.an('array'); expect(placement.floor).to.be.an('object'); + expect(placement.gpid).to.be.an('string'); } }); it('Returns empty data if no valid requests are passed', function () { @@ -135,7 +143,7 @@ describe('ColossussspAdapter', function () { describe('interpretResponse', function () { let resObject = { - body: [ { + body: [{ requestId: '123', mediaType: 'banner', cpm: 0.3, @@ -150,7 +158,7 @@ describe('ColossussspAdapter', function () { advertiserDomains: ['google.com'], advertiserId: 1234 } - } ] + }] }; let serverResponses = spec.interpretResponse(resObject); it('Returns an array of valid server responses if response object is valid', function () { From 23aa14e6f7d0833cefcf1c15f36f2e81ed016c55 Mon Sep 17 00:00:00 2001 From: bretg Date: Fri, 24 Sep 2021 15:31:19 -0400 Subject: [PATCH 16/84] updating user ID module list (#7475) --- modules/.submodules.json | 53 ++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/modules/.submodules.json b/modules/.submodules.json index 87b05dca33d..3ac1e1ef59f 100644 --- a/modules/.submodules.json +++ b/modules/.submodules.json @@ -1,39 +1,40 @@ { "userId": [ - "unifiedIdSystem", - "pubCommonIdSystem", - "id5IdSystem", - "parrableIdSystem", + "admixerIdSystem", + "adtelligentIdSystem", + "akamaiDAPIdSystem", + "amxIdSystem", "britepoolIdSystem", - "liveIntentIdSystem", - "lotamePanoramaId", - "merkleIdSystem", "criteoIdSystem", - "netIdSystem", + "deepintentDpesIdSystem", + "dmdIdSystem", + "fabrickIdSystem", + "flocIdSystem", + "haloIdSystem", + "id5IdSystem", "identityLinkIdSystem", - "sharedIdSystem", + "idxIdSystem", + "imuIdSystem", "intentIqIdSystem", - "zeotapIdPlusIdSystem", - "haloIdSystem", - "quantcastIdSystem", - "deepintentDpesIdSystem", + "kinessoIdSystem", + "liveIntentIdSystem", + "lotamePanoramaIdSystem", + "merkleIdSystem", + "mwOpenLinkIdSystem", + "naveggIdSystem", + "netIdSystem", "nextrollIdSystem", - "idxIdSystem", - "fabrickIdSystem", - "verizonMediaIdSystem", + "novatiqIdSystem", + "parrableIdSystem", "pubProvidedIdSystem", - "mwOpenLinkIdSystem", + "publinkIdSystem", + "quantcastIdSystem", + "sharedIdSystem", "tapadIdSystem", - "novatiqIdSystem", "uid2IdSystem", - "admixerIdSystem", - "dmdIdSystem", - "akamaiDAPId", - "flocIdSystem", - "amxIdSystem", - "naveggId", - "imuIdSystem", - "publinkIdSystem" + "unifiedIdSystem", + "verizonMediaIdSystem", + "zeotapIdPlusIdSystem" ], "adpod": [ "freeWheelAdserverVideo", From cd10ea01e16fd550c2a89061e0bea425276243db Mon Sep 17 00:00:00 2001 From: Jonathan Nadarajah <50102657+jogury@users.noreply.github.com> Date: Mon, 27 Sep 2021 15:46:31 +0200 Subject: [PATCH 17/84] ogury Bid Adapter: fix getusersync method (#7472) --- modules/oguryBidAdapter.js | 2 +- test/spec/modules/oguryBidAdapter_spec.js | 66 +++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/modules/oguryBidAdapter.js b/modules/oguryBidAdapter.js index 2e5342e6f9e..513f9ed384e 100644 --- a/modules/oguryBidAdapter.js +++ b/modules/oguryBidAdapter.js @@ -25,7 +25,7 @@ function getUserSyncs(syncOptions, serverResponses, gdprConsent, uspConsent) { return [{ type: 'image', - url: `${MS_COOKIE_SYNC_DOMAIN}/v1/init-sync/bid-switch?iab_string=${gdprConsent.consentString}&source=prebid` + url: `${MS_COOKIE_SYNC_DOMAIN}/v1/init-sync/bid-switch?iab_string=${(gdprConsent && gdprConsent.consentString) || ''}&source=prebid` }] } diff --git a/test/spec/modules/oguryBidAdapter_spec.js b/test/spec/modules/oguryBidAdapter_spec.js index 0a57690db27..d693e8fd3cc 100644 --- a/test/spec/modules/oguryBidAdapter_spec.js +++ b/test/spec/modules/oguryBidAdapter_spec.js @@ -140,6 +140,72 @@ describe('OguryBidAdapter', function () { syncOptions.pixelEnabled = false; expect(spec.getUserSyncs(syncOptions, [], gdprConsent)).to.have.lengthOf(0); }); + + it('should return syncs array with an element of type image when consentString is undefined', () => { + gdprConsent = { + gdprApplies: true, + consentString: undefined + }; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); + + it('should return syncs array with an element of type image when consentString is null', () => { + gdprConsent = { + gdprApplies: true, + consentString: null + }; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); + + it('should return syncs array with an element of type image when gdprConsent is undefined', () => { + gdprConsent = undefined; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); + + it('should return syncs array with an element of type image when gdprConsent is null', () => { + gdprConsent = null; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); + + it('should return syncs array with an element of type image when gdprConsent is null and gdprApplies is false', () => { + gdprConsent = { + gdprApplies: false, + consentString: null + }; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); + + it('should return syncs array with an element of type image when gdprConsent is empty string and gdprApplies is false', () => { + gdprConsent = { + gdprApplies: false, + consentString: '' + }; + + const userSyncs = spec.getUserSyncs(syncOptions, [], gdprConsent); + expect(userSyncs).to.have.lengthOf(1); + expect(userSyncs[0].type).to.equal('image'); + expect(userSyncs[0].url).to.equal('https://ms-cookie-sync.presage.io/v1/init-sync/bid-switch?iab_string=&source=prebid'); + }); }); describe('buildRequests', function () { From 2f7d3fdef88fe2d70876e18412d71c9c74b3cbad Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 11:04:54 -0700 Subject: [PATCH 18/84] Multiple Bid/Analytics Adapters: import utils functions as needed and not the whole module (#7471) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils as needed; dont import all * import utils as needed; dont import all * Import utils functions as needed; do not import whole module --- modules/adkernelBidAdapter.js | 89 +++++++++++++++-------------- modules/adlooxAdServerVideo.js | 52 ++++++++--------- modules/adlooxAnalyticsAdapter.js | 73 ++++++++++++------------ modules/adlooxRtdProvider.js | 95 ++++++++++++++++--------------- modules/admanBidAdapter.js | 8 +-- modules/admixerBidAdapter.js | 4 +- modules/admixerIdSystem.js | 8 +-- modules/adnowBidAdapter.js | 8 +-- modules/adnuntiusBidAdapter.js | 10 ++-- modules/adoceanBidAdapter.js | 20 +++---- modules/adpartnerBidAdapter.js | 6 +- modules/adpod.js | 87 ++++++++++++++-------------- modules/adprimeBidAdapter.js | 8 +-- modules/adqueryBidAdapter.js | 26 ++++----- modules/adrelevantisBidAdapter.js | 57 ++++++++++--------- 15 files changed, 283 insertions(+), 268 deletions(-) diff --git a/modules/adkernelBidAdapter.js b/modules/adkernelBidAdapter.js index a6bf56f8cad..dcbd8283c71 100644 --- a/modules/adkernelBidAdapter.js +++ b/modules/adkernelBidAdapter.js @@ -1,4 +1,7 @@ -import * as utils from '../src/utils.js'; +import { + isStr, isArray, isPlainObject, deepSetValue, isNumber, deepAccess, getAdUnitSizes, parseGPTSingleSizeArrayToRtbSize, + cleanObj, contains, getDNT, parseUrl, createTrackPixelHtml, _each, isArrayOfNums +} from '../src/utils.js'; import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import find from 'core-js-pure/features/array/find.js'; @@ -154,24 +157,24 @@ export const spec = { prBid.mediaType = NATIVE; prBid.native = buildNativeAd(JSON.parse(rtbBid.adm)); } - if (utils.isStr(rtbBid.dealid)) { + if (isStr(rtbBid.dealid)) { prBid.dealId = rtbBid.dealid; } - if (utils.isArray(rtbBid.adomain)) { - utils.deepSetValue(prBid, 'meta.advertiserDomains', rtbBid.adomain); + if (isArray(rtbBid.adomain)) { + deepSetValue(prBid, 'meta.advertiserDomains', rtbBid.adomain); } - if (utils.isArray(rtbBid.cat)) { - utils.deepSetValue(prBid, 'meta.secondaryCatIds', rtbBid.cat); + if (isArray(rtbBid.cat)) { + deepSetValue(prBid, 'meta.secondaryCatIds', rtbBid.cat); } - if (utils.isPlainObject(rtbBid.ext)) { - if (utils.isNumber(rtbBid.ext.advertiser_id)) { - utils.deepSetValue(prBid, 'meta.advertiserId', rtbBid.ext.advertiser_id); + if (isPlainObject(rtbBid.ext)) { + if (isNumber(rtbBid.ext.advertiser_id)) { + deepSetValue(prBid, 'meta.advertiserId', rtbBid.ext.advertiser_id); } - if (utils.isStr(rtbBid.ext.advertiser_name)) { - utils.deepSetValue(prBid, 'meta.advertiserName', rtbBid.ext.advertiser_name); + if (isStr(rtbBid.ext.advertiser_name)) { + deepSetValue(prBid, 'meta.advertiserName', rtbBid.ext.advertiser_name); } - if (utils.isStr(rtbBid.ext.agency_name)) { - utils.deepSetValue(prBid, 'meta.agencyName', rtbBid.ext.agency_name); + if (isStr(rtbBid.ext.agency_name)) { + deepSetValue(prBid, 'meta.agencyName', rtbBid.ext.agency_name); } } @@ -241,19 +244,19 @@ function buildImp(bidRequest, secure) { var mediaType; var sizes = []; - if (utils.deepAccess(bidRequest, 'mediaTypes.banner')) { - sizes = utils.getAdUnitSizes(bidRequest); + if (deepAccess(bidRequest, 'mediaTypes.banner')) { + sizes = getAdUnitSizes(bidRequest); imp.banner = { - format: sizes.map(wh => utils.parseGPTSingleSizeArrayToRtbSize(wh)), + format: sizes.map(wh => parseGPTSingleSizeArrayToRtbSize(wh)), topframe: 0 }; mediaType = BANNER; - } else if (utils.deepAccess(bidRequest, 'mediaTypes.video')) { - let video = utils.deepAccess(bidRequest, 'mediaTypes.video'); + } else if (deepAccess(bidRequest, 'mediaTypes.video')) { + let video = deepAccess(bidRequest, 'mediaTypes.video'); imp.video = {}; if (video.playerSize) { sizes = video.playerSize[0]; - imp.video = Object.assign(imp.video, utils.parseGPTSingleSizeArrayToRtbSize(sizes) || {}); + imp.video = Object.assign(imp.video, parseGPTSingleSizeArrayToRtbSize(sizes) || {}); } if (bidRequest.params.video) { Object.keys(bidRequest.params.video) @@ -261,7 +264,7 @@ function buildImp(bidRequest, secure) { .forEach(key => imp.video[key] = bidRequest.params.video[key]); } mediaType = VIDEO; - } else if (utils.deepAccess(bidRequest, 'mediaTypes.native')) { + } else if (deepAccess(bidRequest, 'mediaTypes.native')) { let nativeRequest = buildNativeRequest(bidRequest.mediaTypes.native); imp.native = { ver: '1.1', @@ -299,7 +302,7 @@ function buildNativeRequest(nativeReq) { if (desc.assetType === 'img') { assetRoot[desc.assetType] = buildImageAsset(desc, v); } else if (desc.assetType === 'data') { - assetRoot.data = utils.cleanObj({type: desc.type, len: v.len}); + assetRoot.data = cleanObj({type: desc.type, len: v.len}); } else if (desc.assetType === 'title') { assetRoot.title = {len: v.len || 90}; } else { @@ -323,7 +326,7 @@ function buildImageAsset(desc, val) { img.wmin = val.aspect_ratios[0].min_width; img.hmin = val.aspect_ratios[0].min_height; } - return utils.cleanObj(img); + return cleanObj(img); } /** @@ -336,9 +339,9 @@ function isSyncMethodAllowed(syncRule, bidderCode) { if (!syncRule) { return false; } - let bidders = utils.isArray(syncRule.bidders) ? syncRule.bidders : [bidderCode]; + let bidders = isArray(syncRule.bidders) ? syncRule.bidders : [bidderCode]; let rule = syncRule.filter === 'include'; - return utils.contains(bidders, bidderCode) === rule; + return contains(bidders, bidderCode) === rule; } /** @@ -382,33 +385,33 @@ function buildRtbRequest(imps, bidderRequest, schain) { }, 'tmax': parseInt(timeout) }; - if (utils.getDNT()) { + if (getDNT()) { req.device.dnt = 1; } if (gdprConsent) { if (gdprConsent.gdprApplies !== undefined) { - utils.deepSetValue(req, 'regs.ext.gdpr', ~~gdprConsent.gdprApplies); + deepSetValue(req, 'regs.ext.gdpr', ~~gdprConsent.gdprApplies); } if (gdprConsent.consentString !== undefined) { - utils.deepSetValue(req, 'user.ext.consent', gdprConsent.consentString); + deepSetValue(req, 'user.ext.consent', gdprConsent.consentString); } } if (uspConsent) { - utils.deepSetValue(req, 'regs.ext.us_privacy', uspConsent); + deepSetValue(req, 'regs.ext.us_privacy', uspConsent); } if (coppa) { - utils.deepSetValue(req, 'regs.coppa', 1); + deepSetValue(req, 'regs.coppa', 1); } let syncMethod = getAllowedSyncMethod(bidderCode); if (syncMethod) { - utils.deepSetValue(req, 'ext.adk_usersync', syncMethod); + deepSetValue(req, 'ext.adk_usersync', syncMethod); } if (schain) { - utils.deepSetValue(req, 'source.ext.schain', schain); + deepSetValue(req, 'source.ext.schain', schain); } let eids = getExtendedUserIds(bidderRequest); if (eids) { - utils.deepSetValue(req, 'user.ext.eids', eids); + deepSetValue(req, 'user.ext.eids', eids); } return req; } @@ -426,7 +429,7 @@ function getLanguage() { * Creates site description object */ function createSite(refInfo) { - let url = utils.parseUrl(refInfo.referer); + let url = parseUrl(refInfo.referer); let site = { 'domain': url.hostname, 'page': `${url.protocol}://${url.hostname}${url.pathname}` @@ -442,8 +445,8 @@ function createSite(refInfo) { } function getExtendedUserIds(bidderRequest) { - let eids = utils.deepAccess(bidderRequest, 'bids.0.userIdAsEids'); - if (utils.isArray(eids)) { + let eids = deepAccess(bidderRequest, 'bids.0.userIdAsEids'); + if (isArray(eids)) { return eids; } } @@ -455,7 +458,7 @@ function getExtendedUserIds(bidderRequest) { function formatAdMarkup(bid) { let adm = bid.adm; if ('nurl' in bid) { - adm += utils.createTrackPixelHtml(`${bid.nurl}&px=1`); + adm += createTrackPixelHtml(`${bid.nurl}&px=1`); } return adm; } @@ -465,8 +468,8 @@ function formatAdMarkup(bid) { */ function validateNativeAdUnit(adUnit) { return validateNativeImageSize(adUnit.image) && validateNativeImageSize(adUnit.icon) && - !utils.deepAccess(adUnit, 'privacyLink.required') && // not supported yet - !utils.deepAccess(adUnit, 'privacyIcon.required'); // not supported yet + !deepAccess(adUnit, 'privacyLink.required') && // not supported yet + !deepAccess(adUnit, 'privacyIcon.required'); // not supported yet } /** @@ -477,9 +480,9 @@ function validateNativeImageSize(img) { return true; } if (img.sizes) { - return utils.isArrayOfNums(img.sizes, 2); + return isArrayOfNums(img.sizes, 2); } - if (utils.isArray(img.aspect_ratios)) { + if (isArray(img.aspect_ratios)) { return img.aspect_ratios.length > 0 && img.aspect_ratios[0].min_height && img.aspect_ratios[0].min_width; } return true; @@ -496,14 +499,14 @@ function buildNativeAd(nativeResp) { javascriptTrackers: jstracker ? [jstracker] : undefined, privacyLink: privacy, }; - utils._each(assets, asset => { + _each(assets, asset => { let assetName = NATIVE_MODEL[asset.id].name; let assetType = NATIVE_MODEL[asset.id].assetType; - nativeAd[assetName] = asset[assetType].text || asset[assetType].value || utils.cleanObj({ + nativeAd[assetName] = asset[assetType].text || asset[assetType].value || cleanObj({ url: asset[assetType].url, width: asset[assetType].w, height: asset[assetType].h }); }); - return utils.cleanObj(nativeAd); + return cleanObj(nativeAd); } diff --git a/modules/adlooxAdServerVideo.js b/modules/adlooxAdServerVideo.js index 2a61e59b714..7305283039c 100644 --- a/modules/adlooxAdServerVideo.js +++ b/modules/adlooxAdServerVideo.js @@ -11,48 +11,48 @@ import { command as analyticsCommand, COMMAND } from './adlooxAnalyticsAdapter.j import { ajax } from '../src/ajax.js'; import { EVENTS } from '../src/constants.json'; import { targeting } from '../src/targeting.js'; -import * as utils from '../src/utils.js'; +import { logInfo, isFn, logError, isPlainObject, isStr, isBoolean, deepSetValue, deepClone, timestamp, logWarn } from '../src/utils.js'; const MODULE = 'adlooxAdserverVideo'; const URL_VAST = 'https://j.adlooxtracking.com/ads/vast/tag.php'; export function buildVideoUrl(options, callback) { - utils.logInfo(MODULE, 'buildVideoUrl', options); + logInfo(MODULE, 'buildVideoUrl', options); - if (!utils.isFn(callback)) { - utils.logError(MODULE, 'invalid callback'); + if (!isFn(callback)) { + logError(MODULE, 'invalid callback'); return false; } - if (!utils.isPlainObject(options)) { - utils.logError(MODULE, 'missing options'); + if (!isPlainObject(options)) { + logError(MODULE, 'missing options'); return false; } - if (!(options.url_vast === undefined || utils.isStr(options.url_vast))) { - utils.logError(MODULE, 'invalid url_vast options value'); + if (!(options.url_vast === undefined || isStr(options.url_vast))) { + logError(MODULE, 'invalid url_vast options value'); return false; } - if (!(utils.isPlainObject(options.adUnit) || utils.isPlainObject(options.bid))) { - utils.logError(MODULE, "requires either 'adUnit' or 'bid' options value"); + if (!(isPlainObject(options.adUnit) || isPlainObject(options.bid))) { + logError(MODULE, "requires either 'adUnit' or 'bid' options value"); return false; } - if (!utils.isStr(options.url)) { - utils.logError(MODULE, 'invalid url options value'); + if (!isStr(options.url)) { + logError(MODULE, 'invalid url options value'); return false; } - if (!(options.wrap === undefined || utils.isBoolean(options.wrap))) { - utils.logError(MODULE, 'invalid wrap options value'); + if (!(options.wrap === undefined || isBoolean(options.wrap))) { + logError(MODULE, 'invalid wrap options value'); return false; } - if (!(options.blob === undefined || utils.isBoolean(options.blob))) { - utils.logError(MODULE, 'invalid blob options value'); + if (!(options.blob === undefined || isBoolean(options.blob))) { + logError(MODULE, 'invalid blob options value'); return false; } // same logic used in modules/dfpAdServerVideo.js options.bid = options.bid || targeting.getWinningBids(options.adUnit.code)[0]; - utils.deepSetValue(options.bid, 'ext.adloox.video.adserver', true); + deepSetValue(options.bid, 'ext.adloox.video.adserver', true); if (options.wrap !== false) { VASTWrapper(options, callback); @@ -70,7 +70,7 @@ registerVideoSupport('adloox', { function track(options, callback) { callback(options.url); - const bid = utils.deepClone(options.bid); + const bid = deepClone(options.bid); bid.ext.adloox.video.adserver = false; analyticsCommand(COMMAND.TRACK, { @@ -85,13 +85,13 @@ function VASTWrapper(options, callback) { function process(result) { function getAd(xml) { if (!xml || xml.documentElement.tagName != 'VAST') { - utils.logError(MODULE, 'not a VAST tag, using non-wrapped tracking'); + logError(MODULE, 'not a VAST tag, using non-wrapped tracking'); return; } const ads = xml.querySelectorAll('Ad'); if (!ads.length) { - utils.logError(MODULE, 'no VAST ads, using non-wrapped tracking'); + logError(MODULE, 'no VAST ads, using non-wrapped tracking'); return; } @@ -132,7 +132,7 @@ function VASTWrapper(options, callback) { options.url = toBlob(chain[0]); - const epoch = utils.timestamp() - new Date().getTimezoneOffset() * 60 * 1000; + const epoch = timestamp() - new Date().getTimezoneOffset() * 60 * 1000; const expires0 = options.bid.ttl * 1000 - (epoch - options.bid.responseTimestamp); const expires = Math.max(30 * 1000, expires0); setTimeout(function() { urls.forEach(u => URL.revokeObjectURL(u)) }, expires); @@ -154,7 +154,7 @@ function VASTWrapper(options, callback) { const wrapper = getWrapper(ad); if (wrapper) { if (chain.length > 5) { - utils.logWarn(MODULE, `got wrapped tag at depth ${chain.length}, not continuing`); + logWarn(MODULE, `got wrapped tag at depth ${chain.length}, not continuing`); blobify(); return track(options, callback); } @@ -191,7 +191,7 @@ function VASTWrapper(options, callback) { if (duration != 15) args.push([ 'duration', duration ]); if (skip) args.push([ 'skip', skip ]); - utils.logInfo(MODULE, `processed VAST tag chain of depth ${chain.depth}, running callback`); + logInfo(MODULE, `processed VAST tag chain of depth ${chain.depth}, running callback`); analyticsCommand(COMMAND.URL, { url: (options.url_vast || URL_VAST) + '?', @@ -202,7 +202,7 @@ function VASTWrapper(options, callback) { } function fetch(url, withoutcredentials) { - utils.logInfo(MODULE, `fetching VAST ${url}`); + logInfo(MODULE, `fetching VAST ${url}`); ajax(url, { success: function(responseText, q) { @@ -210,10 +210,10 @@ function VASTWrapper(options, callback) { }, error: function(statusText, q) { if (!withoutcredentials) { - utils.logWarn(MODULE, `unable to download (${statusText}), suspected CORS withCredentials problem, retrying without`); + logWarn(MODULE, `unable to download (${statusText}), suspected CORS withCredentials problem, retrying without`); return fetch(url, true); } - utils.logError(MODULE, `failed to fetch (${statusText}), using non-wrapped tracking`); + logError(MODULE, `failed to fetch (${statusText}), using non-wrapped tracking`); process(); } }, undefined, { withCredentials: !withoutcredentials }); diff --git a/modules/adlooxAnalyticsAdapter.js b/modules/adlooxAnalyticsAdapter.js index 17787f816df..6ea1df1b72c 100644 --- a/modules/adlooxAnalyticsAdapter.js +++ b/modules/adlooxAnalyticsAdapter.js @@ -11,7 +11,10 @@ import { auctionManager } from '../src/auctionManager.js'; import { AUCTION_COMPLETED } from '../src/auction.js'; import { EVENTS } from '../src/constants.json'; import find from 'core-js-pure/features/array/find.js'; -import * as utils from '../src/utils.js'; +import { + deepAccess, logInfo, isPlainObject, logError, isStr, isNumber, getGptSlotInfoForAdUnitCode, + isFn, mergeDeep, logMessage, insertElement, logWarn, getUniqueIdentifierStr, parseUrl +} from '../src/utils.js'; const MODULE = 'adlooxAnalyticsAdapter'; @@ -45,7 +48,7 @@ MACRO['creatype'] = function(b, c) { }; MACRO['pbadslot'] = function(b, c) { const adUnit = find(auctionManager.getAdUnits(), a => b.adUnitCode === a.code); - return utils.deepAccess(adUnit, 'ortb2Imp.ext.data.pbadslot') || utils.getGptSlotInfoForAdUnitCode(b.adUnitCode).gptSlot || b.adUnitCode; + return deepAccess(adUnit, 'ortb2Imp.ext.data.pbadslot') || getGptSlotInfoForAdUnitCode(b.adUnitCode).gptSlot || b.adUnitCode; }; MACRO['pbAdSlot'] = MACRO['pbadslot']; // legacy @@ -66,7 +69,7 @@ let analyticsAdapter = Object.assign(adapter({ analyticsType: 'endpoint' }), { track({ eventType, args }) { if (!analyticsAdapter[`handle_${eventType}`]) return; - utils.logInfo(MODULE, 'track', eventType, args); + logInfo(MODULE, 'track', eventType, args); analyticsAdapter[`handle_${eventType}`](args); } @@ -78,45 +81,45 @@ analyticsAdapter.originEnableAnalytics = analyticsAdapter.enableAnalytics; analyticsAdapter.enableAnalytics = function(config) { analyticsAdapter.context = null; - utils.logInfo(MODULE, 'config', config); + logInfo(MODULE, 'config', config); - if (!utils.isPlainObject(config.options)) { - utils.logError(MODULE, 'missing options'); + if (!isPlainObject(config.options)) { + logError(MODULE, 'missing options'); return; } - if (!(config.options.js === undefined || utils.isStr(config.options.js))) { - utils.logError(MODULE, 'invalid js options value'); + if (!(config.options.js === undefined || isStr(config.options.js))) { + logError(MODULE, 'invalid js options value'); return; } - if (!(config.options.toselector === undefined || utils.isFn(config.options.toselector))) { - utils.logError(MODULE, 'invalid toselector options value'); + if (!(config.options.toselector === undefined || isFn(config.options.toselector))) { + logError(MODULE, 'invalid toselector options value'); return; } - if (!utils.isStr(config.options.client)) { - utils.logError(MODULE, 'invalid client options value'); + if (!isStr(config.options.client)) { + logError(MODULE, 'invalid client options value'); return; } - if (!utils.isNumber(config.options.clientid)) { - utils.logError(MODULE, 'invalid clientid options value'); + if (!isNumber(config.options.clientid)) { + logError(MODULE, 'invalid clientid options value'); return; } - if (!utils.isNumber(config.options.tagid)) { - utils.logError(MODULE, 'invalid tagid options value'); + if (!isNumber(config.options.tagid)) { + logError(MODULE, 'invalid tagid options value'); return; } - if (!utils.isNumber(config.options.platformid)) { - utils.logError(MODULE, 'invalid platformid options value'); + if (!isNumber(config.options.platformid)) { + logError(MODULE, 'invalid platformid options value'); return; } - if (!(config.options.params === undefined || utils.isPlainObject(config.options.params))) { - utils.logError(MODULE, 'invalid params options value'); + if (!(config.options.params === undefined || isPlainObject(config.options.params))) { + logError(MODULE, 'invalid params options value'); return; } analyticsAdapter.context = { js: config.options.js || URL_JS, toselector: config.options.toselector || function(bid) { - let code = utils.getGptSlotInfoForAdUnitCode(bid.adUnitCode).divId || bid.adUnitCode; + let code = getGptSlotInfoForAdUnitCode(bid.adUnitCode).divId || bid.adUnitCode; // https://mathiasbynens.be/notes/css-escapes code = code.replace(/^\d/, '\\3$& '); return `#${code}` @@ -128,7 +131,7 @@ analyticsAdapter.enableAnalytics = function(config) { params: [] }; - config.options.params = utils.mergeDeep({}, PARAMS_DEFAULT, config.options.params || {}); + config.options.params = mergeDeep({}, PARAMS_DEFAULT, config.options.params || {}); Object .keys(config.options.params) .forEach(k => { @@ -180,15 +183,15 @@ analyticsAdapter.url = function(url, args, bid) { let n = args.length; while (n-- > 0) { - if (utils.isFn(args[n][1])) { + if (isFn(args[n][1])) { try { args[n][1] = args[n][1](bid); } catch (_) { - utils.logError(MODULE, 'macro', args[n][0], _.message); + logError(MODULE, 'macro', args[n][0], _.message); args[n][1] = `ERROR: ${_.message}`; } } - if (utils.isStr(args[n][1])) { + if (isStr(args[n][1])) { args[n][1] = macros(args[n][1]); } } @@ -200,20 +203,20 @@ analyticsAdapter[`handle_${EVENTS.AUCTION_END}`] = function(auctionDetails) { if (!(auctionDetails.auctionStatus == AUCTION_COMPLETED && auctionDetails.bidsReceived.length > 0)) return; analyticsAdapter[`handle_${EVENTS.AUCTION_END}`] = NOOP; - utils.logMessage(MODULE, 'preloading verification JS'); + logMessage(MODULE, 'preloading verification JS'); - const uri = utils.parseUrl(analyticsAdapter.url(`${analyticsAdapter.context.js}#`)); + const uri = parseUrl(analyticsAdapter.url(`${analyticsAdapter.context.js}#`)); const link = document.createElement('link'); link.setAttribute('href', `${uri.protocol}://${uri.host}${uri.pathname}`); link.setAttribute('rel', 'preload'); link.setAttribute('as', 'script'); - utils.insertElement(link); + insertElement(link); } analyticsAdapter[`handle_${EVENTS.BID_WON}`] = function(bid) { - if (utils.deepAccess(bid, 'ext.adloox.video.adserver')) { - utils.logMessage(MODULE, `measuring '${bid.mediaType}' ad unit code '${bid.adUnitCode}' via Ad Server module`); + if (deepAccess(bid, 'ext.adloox.video.adserver')) { + logMessage(MODULE, `measuring '${bid.mediaType}' ad unit code '${bid.adUnitCode}' via Ad Server module`); return; } @@ -223,11 +226,11 @@ analyticsAdapter[`handle_${EVENTS.BID_WON}`] = function(bid) { el = document.querySelector(sl); } catch (_) { } if (!el) { - utils.logWarn(MODULE, `unable to find ad unit code '${bid.adUnitCode}' slot using selector '${sl}' (use options.toselector to change), ignoring`); + logWarn(MODULE, `unable to find ad unit code '${bid.adUnitCode}' slot using selector '${sl}' (use options.toselector to change), ignoring`); return; } - utils.logMessage(MODULE, `measuring '${bid.mediaType}' unit at '${bid.adUnitCode}'`); + logMessage(MODULE, `measuring '${bid.mediaType}' unit at '${bid.adUnitCode}'`); const params = analyticsAdapter.context.params.concat([ [ 'tagid', '%%tagid%%' ], @@ -257,7 +260,7 @@ export const COMMAND = { TRACK: 'track' }; export function command(cmd, data, callback0) { - const cid = utils.getUniqueIdentifierStr(); + const cid = getUniqueIdentifierStr(); const callback = function() { delete COMMAND_QUEUE[cid]; if (callback0) callback0.apply(null, arguments); @@ -268,7 +271,7 @@ export function command(cmd, data, callback0) { function commandProcess(cid) { const { cmd, data, callback } = COMMAND_QUEUE[cid]; - utils.logInfo(MODULE, 'command', cmd, data); + logInfo(MODULE, 'command', cmd, data); switch (cmd) { case COMMAND.CONFIG: @@ -292,7 +295,7 @@ function commandProcess(cid) { callback(); // drain queue break; default: - utils.logWarn(MODULE, 'command unknown', cmd); + logWarn(MODULE, 'command unknown', cmd); // do not callback as arguments are unknown and to aid debugging } } diff --git a/modules/adlooxRtdProvider.js b/modules/adlooxRtdProvider.js index 3e93047cccc..34d1428ea1d 100644 --- a/modules/adlooxRtdProvider.js +++ b/modules/adlooxRtdProvider.js @@ -16,7 +16,10 @@ import { config as _config } from '../src/config.js'; import { submodule } from '../src/hook.js'; import { ajax } from '../src/ajax.js'; import { getGlobal } from '../src/prebidGlobal.js'; -import * as utils from '../src/utils.js'; +import { + getAdUnitSizes, logInfo, isPlainObject, logError, isStr, isInteger, isArray, isBoolean, mergeDeep, deepAccess, + _each, deepSetValue, logWarn, getGptSlotInfoForAdUnitCode +} from '../src/utils.js'; import includes from 'core-js-pure/features/array/includes.js'; const MODULE_NAME = 'adloox'; @@ -49,7 +52,7 @@ function atf(adUnit, cb) { // Google's advice is to collapse slots on no fill but // we have to cater to clients that grow slots on fill const rect = (function(rect) { - const sizes = utils.getAdUnitSizes(adUnit); + const sizes = getAdUnitSizes(adUnit); if (sizes.length == 0) return false; // interstitial (0x0, 1x1) @@ -141,54 +144,54 @@ function atf(adUnit, cb) { } function init(config, userConsent) { - utils.logInfo(MODULE, 'init', config, userConsent); + logInfo(MODULE, 'init', config, userConsent); - if (!utils.isPlainObject(config)) { - utils.logError(MODULE, 'missing config'); + if (!isPlainObject(config)) { + logError(MODULE, 'missing config'); return false; } if (config.params === undefined) config.params = {}; - if (!(utils.isPlainObject(config.params))) { - utils.logError(MODULE, 'invalid params'); + if (!(isPlainObject(config.params))) { + logError(MODULE, 'invalid params'); return false; } - if (!(config.params.api_origin === undefined || utils.isStr(config.params.api_origin))) { - utils.logError(MODULE, 'invalid api_origin params value'); + if (!(config.params.api_origin === undefined || isStr(config.params.api_origin))) { + logError(MODULE, 'invalid api_origin params value'); return false; } - if (!(config.params.imps === undefined || (utils.isInteger(config.params.imps) && config.params.imps > 0))) { - utils.logError(MODULE, 'invalid imps params value'); + if (!(config.params.imps === undefined || (isInteger(config.params.imps) && config.params.imps > 0))) { + logError(MODULE, 'invalid imps params value'); return false; } - if (!(config.params.freqcap_ip === undefined || (utils.isInteger(config.params.freqcap_ip) && config.params.freqcap_ip >= 0))) { - utils.logError(MODULE, 'invalid freqcap_ip params value'); + if (!(config.params.freqcap_ip === undefined || (isInteger(config.params.freqcap_ip) && config.params.freqcap_ip >= 0))) { + logError(MODULE, 'invalid freqcap_ip params value'); return false; } - if (!(config.params.freqcap_ipua === undefined || (utils.isInteger(config.params.freqcap_ipua) && config.params.freqcap_ipua >= 0))) { - utils.logError(MODULE, 'invalid freqcap_ipua params value'); + if (!(config.params.freqcap_ipua === undefined || (isInteger(config.params.freqcap_ipua) && config.params.freqcap_ipua >= 0))) { + logError(MODULE, 'invalid freqcap_ipua params value'); return false; } - if (!(config.params.thresholds === undefined || (utils.isArray(config.params.thresholds) && config.params.thresholds.every(x => utils.isInteger(x) && x > 0 && x <= 100)))) { - utils.logError(MODULE, 'invalid thresholds params value'); + if (!(config.params.thresholds === undefined || (isArray(config.params.thresholds) && config.params.thresholds.every(x => isInteger(x) && x > 0 && x <= 100)))) { + logError(MODULE, 'invalid thresholds params value'); return false; } - if (!(config.params.slotinpath === undefined || utils.isBoolean(config.params.slotinpath))) { - utils.logError(MODULE, 'invalid slotinpath params value'); + if (!(config.params.slotinpath === undefined || isBoolean(config.params.slotinpath))) { + logError(MODULE, 'invalid slotinpath params value'); return false; } // legacy/deprecated configuration code path - if (!(config.params.params === undefined || (utils.isPlainObject(config.params.params) && utils.isInteger(config.params.params.clientid) && utils.isInteger(config.params.params.tagid) && utils.isInteger(config.params.params.platformid)))) { - utils.logError(MODULE, 'invalid subsection params block'); + if (!(config.params.params === undefined || (isPlainObject(config.params.params) && isInteger(config.params.params.clientid) && isInteger(config.params.params.tagid) && isInteger(config.params.params.platformid)))) { + logError(MODULE, 'invalid subsection params block'); return false; } config.params.thresholds = config.params.thresholds || [ 50, 60, 70, 80, 90 ]; function analyticsConfigCallback(data) { - config = utils.mergeDeep(config.params, data); + config = mergeDeep(config.params, data); } if (config.params.params) { - utils.logWarn(MODULE, `legacy/deprecated configuration (please migrate to ${MODULE_NAME}AnalyticsAdapter)`); + logWarn(MODULE, `legacy/deprecated configuration (please migrate to ${MODULE_NAME}AnalyticsAdapter)`); analyticsConfigCallback(config.params.params); } else { analyticsCommand(COMMAND.CONFIG, null, analyticsConfigCallback); @@ -200,8 +203,8 @@ function init(config, userConsent) { function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { // gptPreAuction runs *after* RTD so pbadslot may not be populated... (╯°□°)╯ ┻━┻ const adUnits = (reqBidsConfigObj.adUnits || getGlobal().adUnits).map(adUnit => { - let path = utils.deepAccess(adUnit, 'ortb2Imp.ext.data.pbadslot'); - if (!path) path = utils.getGptSlotInfoForAdUnitCode(adUnit.code).gptSlot; + let path = deepAccess(adUnit, 'ortb2Imp.ext.data.pbadslot'); + if (!path) path = getGptSlotInfoForAdUnitCode(adUnit.code).gptSlot; return { path: path, unit: adUnit @@ -219,33 +222,33 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { const dataSite = _config.getConfig('ortb2.site.ext.data') || {}; const dataUser = _config.getConfig('ortb2.user.ext.data') || {}; - utils._each(response, (v0, k0) => { + _each(response, (v0, k0) => { if (k0 == '_') return; const k = SEGMENT_HISTORIC[k0] || k0; const v = val(v0, k0); - utils.deepSetValue(k == k0 ? dataUser : dataSite, `${MODULE_NAME}_rtd.${k}`, v); + deepSetValue(k == k0 ? dataUser : dataSite, `${MODULE_NAME}_rtd.${k}`, v); }); - utils.deepSetValue(dataSite, `${MODULE_NAME}_rtd.ok`, true); + deepSetValue(dataSite, `${MODULE_NAME}_rtd.ok`, true); - utils.deepSetValue(ortb2, 'site.ext.data', dataSite); - utils.deepSetValue(ortb2, 'user.ext.data', dataUser); + deepSetValue(ortb2, 'site.ext.data', dataSite); + deepSetValue(ortb2, 'user.ext.data', dataUser); _config.setConfig({ ortb2 }); adUnits.forEach((adUnit, i) => { - utils._each(response['_'][i], (v0, k0) => { + _each(response['_'][i], (v0, k0) => { const k = SEGMENT_HISTORIC[k0] || k0; const v = val(v0, k0); - utils.deepSetValue(adUnit.unit, `ortb2Imp.ext.data.${MODULE_NAME}_rtd.${k}`, v); + deepSetValue(adUnit.unit, `ortb2Imp.ext.data.${MODULE_NAME}_rtd.${k}`, v); }); }); }; - // utils.mergeDeep does not handle merging deep arrays... (╯°□°)╯ ┻━┻ + // mergeDeep does not handle merging deep arrays... (╯°□°)╯ ┻━┻ function mergeDeep(target, ...sources) { function emptyValue(v) { - if (utils.isPlainObject(v)) { + if (isPlainObject(v)) { return {}; - } else if (utils.isArray(v)) { + } else if (isArray(v)) { return []; } else { return undefined; @@ -255,12 +258,12 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { if (!sources.length) return target; const source = sources.shift(); - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + if (isPlainObject(target) && isPlainObject(source)) { Object.keys(source).forEach(key => { if (!(key in target)) target[key] = emptyValue(source[key]); target[key] = target[key] !== undefined ? mergeDeep(target[key], source[key]) : source[key]; }); - } else if (utils.isArray(target) && utils.isArray(source)) { + } else if (isArray(target) && isArray(source)) { source.forEach((v, i) => { if (!(i in target)) target[i] = emptyValue(v); target[i] = target[i] !== undefined ? mergeDeep(target[i], v) : v; @@ -294,7 +297,7 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { ]; if (!adUnits.length) { - utils.logWarn(MODULE, 'no suitable adUnits (missing pbadslot?)'); + logWarn(MODULE, 'no suitable adUnits (missing pbadslot?)'); } const atfQueue = []; adUnits.map((adUnit, i) => { @@ -307,7 +310,7 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { atf(adUnit.unit, function(x) { let viewable = document.visibilityState === undefined || document.visibilityState == 'visible'; try { viewable = viewable && top.document.hasFocus() } catch (_) {} - utils.logInfo(MODULE, `atf code=${adUnit.unit.code} has area=${x}, viewable=${viewable}`); + logInfo(MODULE, `atf code=${adUnit.unit.code} has area=${x}, viewable=${viewable}`); const atfList = []; atfList[i] = { atf: parseInt(x * 100) }; response = mergeDeep(response, { _: atfList }); semaphoreInc(-1); @@ -336,12 +339,12 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { throw false; } } catch (_) { - utils.logError(MODULE, 'unexpected response'); + logError(MODULE, 'unexpected response'); } semaphoreInc(-1); }, error: function(statusText, q) { - utils.logError(MODULE, 'request failed'); + logError(MODULE, 'request failed'); semaphoreInc(-1); } }); @@ -350,8 +353,8 @@ function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { function getTargetingData(adUnitArray, config, userConsent) { function targetingNormalise(v) { - if (utils.isArray(v) && v.length == 0) return undefined; - if (utils.isBoolean(v)) v = ~~v; + if (isArray(v) && v.length == 0) return undefined; + if (isBoolean(v)) v = ~~v; if (!v) return undefined; // empty string and zero return v; } @@ -363,14 +366,14 @@ function getTargetingData(adUnitArray, config, userConsent) { return getGlobal().adUnits.filter(adUnit => includes(adUnitArray, adUnit.code)).reduce((a, adUnit) => { a[adUnit.code] = {}; - utils._each(dataSite, (v0, k) => { + _each(dataSite, (v0, k) => { if (includes(SEGMENT_HISTORIC_VALUES, k)) return; // ignore site average viewability const v = targetingNormalise(v0); if (v) a[adUnit.code][ADSERVER_TARGETING_PREFIX + k] = v; }); - const adUnitSegments = utils.deepAccess(adUnit, `ortb2Imp.ext.data.${MODULE_NAME}_rtd`, {}); - utils._each(Object.assign({}, dataUser, adUnitSegments), (v0, k) => { + const adUnitSegments = deepAccess(adUnit, `ortb2Imp.ext.data.${MODULE_NAME}_rtd`, {}); + _each(Object.assign({}, dataUser, adUnitSegments), (v0, k) => { const v = targetingNormalise(v0); if (v) a[adUnit.code][ADSERVER_TARGETING_PREFIX + k] = v; }); diff --git a/modules/admanBidAdapter.js b/modules/admanBidAdapter.js index 18d1fb57486..e02a1a9df04 100644 --- a/modules/admanBidAdapter.js +++ b/modules/admanBidAdapter.js @@ -1,6 +1,6 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { isFn, deepAccess, logMessage } from '../src/utils.js'; const BIDDER_CODE = 'adman'; const AD_URL = 'https://pub.admanmedia.com/?c=o&m=multi'; @@ -24,8 +24,8 @@ function isBidResponseValid(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -69,7 +69,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; let placements = []; let request = { diff --git a/modules/admixerBidAdapter.js b/modules/admixerBidAdapter.js index bb9a6dd44a3..e136dfcfbdb 100644 --- a/modules/admixerBidAdapter.js +++ b/modules/admixerBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logError } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {config} from '../src/config.js'; @@ -61,7 +61,7 @@ export const spec = { const {body: {ads = []} = {}} = serverResponse; ads.forEach((ad) => bidResponses.push(ad)); } catch (e) { - utils.logError(e); + logError(e); } return bidResponses; }, diff --git a/modules/admixerIdSystem.js b/modules/admixerIdSystem.js index c963f1e5b88..49ffe4f4680 100644 --- a/modules/admixerIdSystem.js +++ b/modules/admixerIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logError, logInfo } from '../src/utils.js' import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -43,13 +43,13 @@ export const admixerIdSubmodule = { getId(config, consentData) { const {e, p, pid} = (config && config.params) || {}; if (!pid || typeof pid !== 'string') { - utils.logError('admixerId submodule requires partner id to be defined'); + logError('admixerId submodule requires partner id to be defined'); return; } const gdpr = (consentData && typeof consentData.gdprApplies === 'boolean' && consentData.gdprApplies) ? 1 : 0; const consentString = gdpr ? consentData.consentString : ''; if (gdpr && !consentString) { - utils.logInfo('Consent string is required to call admixer id.'); + logInfo('Consent string is required to call admixer id.'); return; } const url = `https://inv-nets.admixer.net/cntcm.aspx?ssp=${pid}${e ? `&e=${e}` : ''}${p ? `&p=${p}` : ''}${consentString ? `&cs=${consentString}` : ''}`; @@ -83,7 +83,7 @@ function retrieveVisitorId(url, callback) { } }, error: error => { - utils.logInfo(`admixerId: fetch encountered an error`, error); + logInfo(`admixerId: fetch encountered an error`, error); callback(); } }, undefined, { method: 'GET', withCredentials: true }); diff --git a/modules/adnowBidAdapter.js b/modules/adnowBidAdapter.js index 7412db8d7b6..badf57ed5c9 100644 --- a/modules/adnowBidAdapter.js +++ b/modules/adnowBidAdapter.js @@ -1,6 +1,6 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { NATIVE, BANNER } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { parseSizesInput, deepAccess, parseQueryStringParameters } from '../src/utils.js'; import includes from 'core-js-pure/features/array/includes.js'; const BIDDER_CODE = 'adnow'; @@ -61,13 +61,13 @@ export const spec = { }; if (mediaType === BANNER) { - data.sizes = utils.parseSizesInput( + data.sizes = parseSizesInput( req.mediaTypes && req.mediaTypes.banner && req.mediaTypes.banner.sizes ).join('|') } else { data.width = data.height = 200; - let sizes = utils.deepAccess(req, 'mediaTypes.native.image.sizes', []); + let sizes = deepAccess(req, 'mediaTypes.native.image.sizes', []); if (sizes.length > 0) { const size = Array.isArray(sizes[0]) ? sizes[0] : sizes; @@ -81,7 +81,7 @@ export const spec = { return { method: 'GET', url: ENDPOINT, - data: utils.parseQueryStringParameters(data), + data: parseQueryStringParameters(data), options: { withCredentials: false, crossOrigin: true diff --git a/modules/adnuntiusBidAdapter.js b/modules/adnuntiusBidAdapter.js index 68c3e9caffd..4429e37f091 100644 --- a/modules/adnuntiusBidAdapter.js +++ b/modules/adnuntiusBidAdapter.js @@ -1,6 +1,6 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { isStr, deepAccess } from '../src/utils.js'; import { config } from '../src/config.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -9,12 +9,12 @@ const ENDPOINT_URL = 'https://ads.adnuntius.delivery/i'; const GVLID = 855; const checkSegment = function (segment) { - if (utils.isStr(segment)) return segment; + if (isStr(segment)) return segment; if (segment.id) return segment.id } const getSegmentsFromOrtb = function (ortb2) { - const userData = utils.deepAccess(ortb2, 'user.data'); + const userData = deepAccess(ortb2, 'user.data'); let segments = []; if (userData) { userData.forEach(userdat => { @@ -59,8 +59,8 @@ export const spec = { const usi = getUsi(adnMeta, ortb2, bidderRequest) const segments = getSegmentsFromOrtb(ortb2); const tzo = new Date().getTimezoneOffset(); - const gdprApplies = utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies'); - const consentString = utils.deepAccess(bidderRequest, 'gdprConsent.consentString'); + const gdprApplies = deepAccess(bidderRequest, 'gdprConsent.gdprApplies'); + const consentString = deepAccess(bidderRequest, 'gdprConsent.consentString'); request.push('tzo=' + tzo) request.push('format=json') diff --git a/modules/adoceanBidAdapter.js b/modules/adoceanBidAdapter.js index 7ce9c7ae8f2..0c23f5e3d8a 100644 --- a/modules/adoceanBidAdapter.js +++ b/modules/adoceanBidAdapter.js @@ -1,11 +1,11 @@ -import * as utils from '../src/utils.js'; +import { _each, parseSizesInput, isStr, isArray } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'adocean'; function buildEndpointUrl(emiter, payloadMap) { const payload = []; - utils._each(payloadMap, function(v, k) { + _each(payloadMap, function(v, k) { payload.push(k + '=' + encodeURIComponent(v)); }); @@ -26,12 +26,12 @@ function buildRequest(masterBidRequests, masterId, gdprConsent) { const bidIdMap = {}; - utils._each(masterBidRequests, function(bid, slaveId) { + _each(masterBidRequests, function(bid, slaveId) { if (!emiter) { emiter = bid.params.emiter; } - const slaveSizes = utils.parseSizesInput(bid.mediaTypes.banner.sizes).join('_'); + const slaveSizes = parseSizesInput(bid.mediaTypes.banner.sizes).join('_'); const rawSlaveId = bid.params.slaveId.replace('adocean', ''); payload.aosspsizes.push(rawSlaveId + '~' + slaveSizes); @@ -95,7 +95,7 @@ export const spec = { isBidRequestValid: function(bid) { const requiredParams = ['slaveId', 'masterId', 'emiter']; - if (requiredParams.some(name => !utils.isStr(bid.params[name]) || !bid.params[name].length)) { + if (requiredParams.some(name => !isStr(bid.params[name]) || !bid.params[name].length)) { return false; } @@ -106,12 +106,12 @@ export const spec = { const bidRequestsByMaster = {}; let requests = []; - utils._each(validBidRequests, function(bidRequest) { + _each(validBidRequests, function(bidRequest) { assignToMaster(bidRequest, bidRequestsByMaster); }); - utils._each(bidRequestsByMaster, function(masterRequests, masterId) { - utils._each(masterRequests, function(instanceRequests) { + _each(bidRequestsByMaster, function(masterRequests, masterId) { + _each(masterRequests, function(instanceRequests) { requests.push(buildRequest(instanceRequests, masterId, bidderRequest.gdprConsent)); }); }); @@ -122,8 +122,8 @@ export const spec = { interpretResponse: function(serverResponse, bidRequest) { let bids = []; - if (utils.isArray(serverResponse.body)) { - utils._each(serverResponse.body, function(placementResponse) { + if (isArray(serverResponse.body)) { + _each(serverResponse.body, function(placementResponse) { interpretResponse(placementResponse, bidRequest, bids); }); } diff --git a/modules/adpartnerBidAdapter.js b/modules/adpartnerBidAdapter.js index e8942884a9c..e8d8a43aa1b 100644 --- a/modules/adpartnerBidAdapter.js +++ b/modules/adpartnerBidAdapter.js @@ -1,5 +1,5 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js' +import { buildUrl } from '../src/utils.js' import {ajax} from '../src/ajax.js'; const BIDDER_CODE = 'adpartner'; @@ -64,7 +64,7 @@ export const spec = { beaconParams.tag = beaconParams.tag.join(','); beaconParams.sizes = beaconParams.sizes.join(','); - let adPartnerRequestUrl = utils.buildUrl({ + let adPartnerRequestUrl = buildUrl({ protocol: ENDPOINT_PROTOCOL, hostname: ENDPOINT_DOMAIN, pathname: ENDPOINT_PATH, @@ -127,7 +127,7 @@ export const spec = { onBidWon: function(data) { data.winNotification.forEach(function(unitWon) { - let adPartnerBidWonUrl = utils.buildUrl({ + let adPartnerBidWonUrl = buildUrl({ protocol: ENDPOINT_PROTOCOL, hostname: ENDPOINT_DOMAIN, pathname: unitWon.path diff --git a/modules/adpod.js b/modules/adpod.js index 57baf5b5fc6..ddceed1c344 100644 --- a/modules/adpod.js +++ b/modules/adpod.js @@ -12,7 +12,10 @@ * module that designed to support adpod video type ads. This import process allows this module to effectively act as a sub-module. */ -import * as utils from '../src/utils.js'; +import { + generateUUID, deepAccess, logWarn, logInfo, isArrayOfNums, isArray, isNumber, logError, groupBy, compareOn, + isPlainObject +} from '../src/utils.js'; import { addBidToAuction, doCallbacksIfTimedout, AUCTION_IN_PROGRESS, callPrebidCache, getPriceByGranularity, getPriceGranularity } from '../src/auction.js'; import { checkAdUnitSetup } from '../src/prebid.js'; import { checkVideoBidSetup } from '../src/video.js'; @@ -45,7 +48,7 @@ function createBidCacheRegistry() { registry[auctionId] = {}; registry[auctionId].bidStorage = new Set(); registry[auctionId].queueDispatcher = createDispatcher(queueTimeDelay); - registry[auctionId].initialCacheKey = utils.generateUUID(); + registry[auctionId].initialCacheKey = generateUUID(); } return { @@ -68,7 +71,7 @@ function createBidCacheRegistry() { setupInitialCacheKey: function (bid) { if (!registry[bid.auctionId]) { registry[bid.auctionId] = {}; - registry[bid.auctionId].initialCacheKey = utils.generateUUID(); + registry[bid.auctionId].initialCacheKey = generateUUID(); } }, getInitialCacheKey: function (bid) { @@ -115,9 +118,9 @@ function createDispatcher(timeoutDuration) { function getPricePartForAdpodKey(bid) { let pricePart let prioritizeDeals = config.getConfig('adpod.prioritizeDeals'); - if (prioritizeDeals && utils.deepAccess(bid, 'video.dealTier')) { + if (prioritizeDeals && deepAccess(bid, 'video.dealTier')) { const adpodDealPrefix = config.getConfig(`adpod.dealTier.${bid.bidderCode}.prefix`); - pricePart = (adpodDealPrefix) ? adpodDealPrefix + utils.deepAccess(bid, 'video.dealTier') : utils.deepAccess(bid, 'video.dealTier'); + pricePart = (adpodDealPrefix) ? adpodDealPrefix + deepAccess(bid, 'video.dealTier') : deepAccess(bid, 'video.dealTier'); } else { const granularity = getPriceGranularity(bid.mediaType); pricePart = getPriceByGranularity(granularity)(bid); @@ -132,12 +135,12 @@ function getPricePartForAdpodKey(bid) { */ function attachPriceIndustryDurationKeyToBid(bid, brandCategoryExclusion) { let initialCacheKey = bidCacheRegistry.getInitialCacheKey(bid); - let duration = utils.deepAccess(bid, 'video.durationBucket'); + let duration = deepAccess(bid, 'video.durationBucket'); const pricePart = getPricePartForAdpodKey(bid); let pcd; if (brandCategoryExclusion) { - let category = utils.deepAccess(bid, 'meta.adServerCatId'); + let category = deepAccess(bid, 'meta.adServerCatId'); pcd = `${pricePart}_${category}_${duration}s`; } else { pcd = `${pricePart}_${duration}s`; @@ -168,7 +171,7 @@ function updateBidQueue(auctionInstance, bidResponse, afterBidAdded) { let killQueue = !!(auctionInstance.getAuctionStatus() !== AUCTION_IN_PROGRESS); callDispatcher(auctionInstance, bidListArr, afterBidAdded, killQueue); } else { - utils.logWarn('Attempted to cache a bid from an unknown auction. Bid:', bidResponse); + logWarn('Attempted to cache a bid from an unknown auction. Bid:', bidResponse); } } @@ -196,7 +199,7 @@ function firePrebidCacheCall(auctionInstance, bidList, afterBidAdded) { store(bidList, function (error, cacheIds) { if (error) { - utils.logWarn(`Failed to save to the video cache: ${error}. Video bid(s) must be discarded.`); + logWarn(`Failed to save to the video cache: ${error}. Video bid(s) must be discarded.`); for (let i = 0; i < bidList.length; i++) { doCallbacksIfTimedout(auctionInstance, bidList[i]); } @@ -206,7 +209,7 @@ function firePrebidCacheCall(auctionInstance, bidList, afterBidAdded) { if (cacheIds[i].uuid !== '') { addBidToAuction(auctionInstance, bidList[i]); } else { - utils.logInfo(`Detected a bid was not cached because the custom key was already registered. Attempted to use key: ${bidList[i].customCacheKey}. Bid was: `, bidList[i]); + logInfo(`Detected a bid was not cached because the custom key was already registered. Attempted to use key: ${bidList[i].customCacheKey}. Bid was: `, bidList[i]); } afterBidAdded(); } @@ -223,12 +226,12 @@ function firePrebidCacheCall(auctionInstance, bidList, afterBidAdded) { * @param {Object} bidderRequest copy of bid's associated bidderRequest object */ export function callPrebidCacheHook(fn, auctionInstance, bidResponse, afterBidAdded, bidderRequest) { - let videoConfig = utils.deepAccess(bidderRequest, 'mediaTypes.video'); + let videoConfig = deepAccess(bidderRequest, 'mediaTypes.video'); if (videoConfig && videoConfig.context === ADPOD) { let brandCategoryExclusion = config.getConfig('adpod.brandCategoryExclusion'); - let adServerCatId = utils.deepAccess(bidResponse, 'meta.adServerCatId'); + let adServerCatId = deepAccess(bidResponse, 'meta.adServerCatId'); if (!adServerCatId && brandCategoryExclusion) { - utils.logWarn('Detected a bid without meta.adServerCatId while setConfig({adpod.brandCategoryExclusion}) was enabled. This bid has been rejected:', bidResponse) + logWarn('Detected a bid without meta.adServerCatId while setConfig({adpod.brandCategoryExclusion}) was enabled. This bid has been rejected:', bidResponse) afterBidAdded(); } else { if (config.getConfig('adpod.deferCaching') === false) { @@ -260,12 +263,12 @@ export function callPrebidCacheHook(fn, auctionInstance, bidResponse, afterBidAd */ export function checkAdUnitSetupHook(fn, adUnits) { let goodAdUnits = adUnits.filter(adUnit => { - let mediaTypes = utils.deepAccess(adUnit, 'mediaTypes'); - let videoConfig = utils.deepAccess(mediaTypes, 'video'); + let mediaTypes = deepAccess(adUnit, 'mediaTypes'); + let videoConfig = deepAccess(mediaTypes, 'video'); if (videoConfig && videoConfig.context === ADPOD) { // run check to see if other mediaTypes are defined (ie multi-format); reject adUnit if so if (Object.keys(mediaTypes).length > 1) { - utils.logWarn(`Detected more than one mediaType in adUnitCode: ${adUnit.code} while attempting to define an 'adpod' video adUnit. 'adpod' adUnits cannot be mixed with other mediaTypes. This adUnit will be removed from the auction.`); + logWarn(`Detected more than one mediaType in adUnitCode: ${adUnit.code} while attempting to define an 'adpod' video adUnit. 'adpod' adUnits cannot be mixed with other mediaTypes. This adUnit will be removed from the auction.`); return false; } @@ -274,20 +277,20 @@ export function checkAdUnitSetupHook(fn, adUnits) { let playerSize = !!( ( videoConfig.playerSize && ( - utils.isArrayOfNums(videoConfig.playerSize, 2) || ( - utils.isArray(videoConfig.playerSize) && videoConfig.playerSize.every(sz => utils.isArrayOfNums(sz, 2)) + isArrayOfNums(videoConfig.playerSize, 2) || ( + isArray(videoConfig.playerSize) && videoConfig.playerSize.every(sz => isArrayOfNums(sz, 2)) ) ) ) || (videoConfig.sizeConfig) ); - let adPodDurationSec = !!(videoConfig.adPodDurationSec && utils.isNumber(videoConfig.adPodDurationSec) && videoConfig.adPodDurationSec > 0); - let durationRangeSec = !!(videoConfig.durationRangeSec && utils.isArrayOfNums(videoConfig.durationRangeSec) && videoConfig.durationRangeSec.every(range => range > 0)); + let adPodDurationSec = !!(videoConfig.adPodDurationSec && isNumber(videoConfig.adPodDurationSec) && videoConfig.adPodDurationSec > 0); + let durationRangeSec = !!(videoConfig.durationRangeSec && isArrayOfNums(videoConfig.durationRangeSec) && videoConfig.durationRangeSec.every(range => range > 0)); if (!playerSize || !adPodDurationSec || !durationRangeSec) { errMsg += (!playerSize) ? '\nmediaTypes.video.playerSize' : ''; errMsg += (!adPodDurationSec) ? '\nmediaTypes.video.adPodDurationSec' : ''; errMsg += (!durationRangeSec) ? '\nmediaTypes.video.durationRangeSec' : ''; - utils.logWarn(errMsg); + logWarn(errMsg); return false; } } @@ -313,8 +316,8 @@ export function checkAdUnitSetupHook(fn, adUnits) { */ function checkBidDuration(bidderRequest, bidResponse) { const buffer = 2; - let bidDuration = utils.deepAccess(bidResponse, 'video.durationSeconds'); - let videoConfig = utils.deepAccess(bidderRequest, 'mediaTypes.video'); + let bidDuration = deepAccess(bidResponse, 'video.durationSeconds'); + let videoConfig = deepAccess(bidderRequest, 'mediaTypes.video'); let adUnitRanges = videoConfig.durationRangeSec; adUnitRanges.sort((a, b) => a - b); // ensure the ranges are sorted in numeric order @@ -324,14 +327,14 @@ function checkBidDuration(bidderRequest, bidResponse) { let nextHighestRange = find(adUnitRanges, range => (range + buffer) >= bidDuration); bidResponse.video.durationBucket = nextHighestRange; } else { - utils.logWarn(`Detected a bid with a duration value outside the accepted ranges specified in adUnit.mediaTypes.video.durationRangeSec. Rejecting bid: `, bidResponse); + logWarn(`Detected a bid with a duration value outside the accepted ranges specified in adUnit.mediaTypes.video.durationRangeSec. Rejecting bid: `, bidResponse); return false; } } else { if (find(adUnitRanges, range => range === bidDuration)) { bidResponse.video.durationBucket = bidDuration; } else { - utils.logWarn(`Detected a bid with a duration value not part of the list of accepted ranges specified in adUnit.mediaTypes.video.durationRangeSec. Exact match durations must be used for this adUnit. Rejecting bid: `, bidResponse); + logWarn(`Detected a bid with a duration value not part of the list of accepted ranges specified in adUnit.mediaTypes.video.durationRangeSec. Exact match durations must be used for this adUnit. Rejecting bid: `, bidResponse); return false; } } @@ -352,16 +355,16 @@ export function checkVideoBidSetupHook(fn, bid, bidRequest, videoMediaType, cont if (context === ADPOD) { let result = true; let brandCategoryExclusion = config.getConfig('adpod.brandCategoryExclusion'); - if (brandCategoryExclusion && !utils.deepAccess(bid, 'meta.primaryCatId')) { + if (brandCategoryExclusion && !deepAccess(bid, 'meta.primaryCatId')) { result = false; } - if (utils.deepAccess(bid, 'video')) { - if (!utils.deepAccess(bid, 'video.context') || bid.video.context !== ADPOD) { + if (deepAccess(bid, 'video')) { + if (!deepAccess(bid, 'video.context') || bid.video.context !== ADPOD) { result = false; } - if (!utils.deepAccess(bid, 'video.durationSeconds') || bid.video.durationSeconds <= 0) { + if (!deepAccess(bid, 'video.durationSeconds') || bid.video.durationSeconds <= 0) { result = false; } else { let isBidGood = checkBidDuration(bidRequest, bid); @@ -370,7 +373,7 @@ export function checkVideoBidSetupHook(fn, bid, bidRequest, videoMediaType, cont } if (!config.getConfig('cache.url') && bid.vastXml && !bid.vastUrl) { - utils.logError(` + logError(` This bid contains only vastXml and will not work when a prebid cache url is not specified. Try enabling prebid cache with pbjs.setConfig({ cache: {url: "..."} }); `); @@ -392,7 +395,7 @@ export function adpodSetConfig(config) { if (typeof config.bidQueueTimeDelay === 'number' && config.bidQueueTimeDelay > 0) { queueTimeDelay = config.bidQueueTimeDelay; } else { - utils.logWarn(`Detected invalid value for adpod.bidQueueTimeDelay in setConfig; must be a positive number. Using default: ${queueTimeDelay}`) + logWarn(`Detected invalid value for adpod.bidQueueTimeDelay in setConfig; must be a positive number. Using default: ${queueTimeDelay}`) } } @@ -400,7 +403,7 @@ export function adpodSetConfig(config) { if (typeof config.bidQueueSizeLimit === 'number' && config.bidQueueSizeLimit > 0) { queueSizeLimit = config.bidQueueSizeLimit; } else { - utils.logWarn(`Detected invalid value for adpod.bidQueueSizeLimit in setConfig; must be a positive number. Using default: ${queueSizeLimit}`) + logWarn(`Detected invalid value for adpod.bidQueueSizeLimit in setConfig; must be a positive number. Using default: ${queueSizeLimit}`) } } } @@ -464,7 +467,7 @@ export function sortByPricePerSecond(a, b) { */ export function getTargeting({ codes, callback } = {}) { if (!callback) { - utils.logError('No callback function was defined in the getTargeting call. Aborting getTargeting().'); + logError('No callback function was defined in the getTargeting call. Aborting getTargeting().'); return; } codes = codes || []; @@ -480,7 +483,7 @@ export function getTargeting({ codes, callback } = {}) { let prioritizeDeals = config.getConfig('adpod.prioritizeDeals'); if (prioritizeDeals) { let [otherBids, highPriorityDealBids] = bids.reduce((partitions, bid) => { - let bidDealTier = utils.deepAccess(bid, 'video.dealTier'); + let bidDealTier = deepAccess(bid, 'video.dealTier'); let minDealTier = config.getConfig(`adpod.dealTier.${bid.bidderCode}.minDealTier`); if (minDealTier && bidDealTier) { if (bidDealTier >= minDealTier) { @@ -506,7 +509,7 @@ export function getTargeting({ codes, callback } = {}) { if (deferCachingEnabled === false) { adPodAdUnits.forEach((adUnit) => { let adPodTargeting = []; - let adPodDurationSeconds = utils.deepAccess(adUnit, 'mediaTypes.video.adPodDurationSec'); + let adPodDurationSeconds = deepAccess(adUnit, 'mediaTypes.video.adPodDurationSec'); bids .filter((bid) => bid.adUnitCode === adUnit.code) @@ -530,7 +533,7 @@ export function getTargeting({ codes, callback } = {}) { } else { let bidsToCache = []; adPodAdUnits.forEach((adUnit) => { - let adPodDurationSeconds = utils.deepAccess(adUnit, 'mediaTypes.video.adPodDurationSec'); + let adPodDurationSeconds = deepAccess(adUnit, 'mediaTypes.video.adPodDurationSec'); bids .filter((bid) => bid.adUnitCode === adUnit.code) @@ -546,7 +549,7 @@ export function getTargeting({ codes, callback } = {}) { if (error) { callback(error, null); } else { - let groupedBids = utils.groupBy(bidsSuccessfullyCached, 'adUnitCode'); + let groupedBids = groupBy(bidsSuccessfullyCached, 'adUnitCode'); Object.keys(groupedBids).forEach((adUnitCode) => { let adPodTargeting = []; @@ -578,7 +581,7 @@ export function getTargeting({ codes, callback } = {}) { */ function getAdPodAdUnits(codes) { return auctionManager.getAdUnits() - .filter((adUnit) => utils.deepAccess(adUnit, 'mediaTypes.video.context') === ADPOD) + .filter((adUnit) => deepAccess(adUnit, 'mediaTypes.video.context') === ADPOD) .filter((adUnit) => (codes.length > 0) ? codes.indexOf(adUnit.code) != -1 : true); } @@ -590,10 +593,10 @@ function getAdPodAdUnits(codes) { function getExclusiveBids(bidsReceived) { let bids = bidsReceived .map((bid) => Object.assign({}, bid, { [TARGETING_KEY_PB_CAT_DUR]: bid.adserverTargeting[TARGETING_KEY_PB_CAT_DUR] })); - bids = utils.groupBy(bids, TARGETING_KEY_PB_CAT_DUR); + bids = groupBy(bids, TARGETING_KEY_PB_CAT_DUR); let filteredBids = []; Object.keys(bids).forEach((targetingKey) => { - bids[targetingKey].sort(utils.compareOn('responseTimestamp')); + bids[targetingKey].sort(compareOn('responseTimestamp')); filteredBids.push(bids[targetingKey][0]); }); return filteredBids; @@ -619,8 +622,8 @@ const sharedMethods = { Object.freeze(sharedMethods); module('adpod', function shareAdpodUtilities(...args) { - if (!utils.isPlainObject(args[0])) { - utils.logError('Adpod module needs plain object to share methods with submodule'); + if (!isPlainObject(args[0])) { + logError('Adpod module needs plain object to share methods with submodule'); return; } function addMethods(object, func) { diff --git a/modules/adprimeBidAdapter.js b/modules/adprimeBidAdapter.js index ef370301184..2b5a7e15af2 100644 --- a/modules/adprimeBidAdapter.js +++ b/modules/adprimeBidAdapter.js @@ -1,6 +1,6 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { isFn, deepAccess, logMessage } from '../src/utils.js'; const BIDDER_CODE = 'adprime'; const AD_URL = 'https://delta.adprime.com/pbjs'; @@ -24,8 +24,8 @@ function isBidResponseValid(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -56,7 +56,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; let placements = []; let request = { diff --git a/modules/adqueryBidAdapter.js b/modules/adqueryBidAdapter.js index bbff7edea47..ce31f64d705 100644 --- a/modules/adqueryBidAdapter.js +++ b/modules/adqueryBidAdapter.js @@ -1,6 +1,6 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER} from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { logInfo, buildUrl, triggerPixel } from '../src/utils.js'; import { getStorageManager } from '../src/storageManager.js'; const ADQUERY_GVLID = 902; @@ -55,8 +55,8 @@ export const spec = { * @return {Bid[]} */ interpretResponse: (response, request) => { - utils.logInfo(request); - utils.logInfo(response); + logInfo(request); + logInfo(response); const res = response && response.body && response.body.data; let bidResponses = []; @@ -84,7 +84,7 @@ export const spec = { } }; bidResponses.push(bidResponse); - utils.logInfo('bidResponses', bidResponses); + logInfo('bidResponses', bidResponses); return bidResponses; }, @@ -96,7 +96,7 @@ export const spec = { if (timeoutData == null) { return; } - utils.logInfo('onTimeout ', timeoutData); + logInfo('onTimeout ', timeoutData); let params = { bidder: timeoutData.bidder, bId: timeoutData.bidId, @@ -104,40 +104,40 @@ export const spec = { timeout: timeoutData.timeout, auctionId: timeoutData.auctionId, }; - let adqueryRequestUrl = utils.buildUrl({ + let adqueryRequestUrl = buildUrl({ protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, hostname: ADQUERY_BIDDER_DOMAIN, pathname: '/prebid/eventTimeout', search: params }); - utils.triggerPixel(adqueryRequestUrl); + triggerPixel(adqueryRequestUrl); }, /** * @param {Bid} bid */ onBidWon: (bid) => { - utils.logInfo('onBidWon', bid); + logInfo('onBidWon', bid); const bidString = JSON.stringify(bid); const encodedBuf = window.btoa(bidString); let params = { q: encodedBuf, }; - let adqueryRequestUrl = utils.buildUrl({ + let adqueryRequestUrl = buildUrl({ protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, hostname: ADQUERY_BIDDER_DOMAIN, pathname: '/prebid/eventBidWon', search: params }); - utils.triggerPixel(adqueryRequestUrl); + triggerPixel(adqueryRequestUrl); }, /** * @param {Bid} bid */ onSetTargeting: (bid) => { - utils.logInfo('onSetTargeting', bid); + logInfo('onSetTargeting', bid); let params = { bidder: bid.bidder, @@ -150,13 +150,13 @@ export const spec = { adUnitCode: bid.adUnitCode }; - let adqueryRequestUrl = utils.buildUrl({ + let adqueryRequestUrl = buildUrl({ protocol: ADQUERY_BIDDER_DOMAIN_PROTOCOL, hostname: ADQUERY_BIDDER_DOMAIN, pathname: '/prebid/eventSetTargeting', search: params }); - utils.triggerPixel(adqueryRequestUrl); + triggerPixel(adqueryRequestUrl); }, getUserSyncs: (syncOptions, serverResponses, gdprConsent, uspConsent) => { let syncUrl = ADQUERY_USER_SYNC_DOMAIN; diff --git a/modules/adrelevantisBidAdapter.js b/modules/adrelevantisBidAdapter.js index b6832cfeb0d..649031d1e3b 100644 --- a/modules/adrelevantisBidAdapter.js +++ b/modules/adrelevantisBidAdapter.js @@ -1,5 +1,8 @@ import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; +import { + logError, convertTypes, convertCamelToUnderscore, isArray, deepClone, logWarn, logMessage, getBidRequest, deepAccess, + isStr, createTrackPixelHtml, isEmpty, transformBidderParamKeywords, chunk, isArrayOfNums +} from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; @@ -145,7 +148,7 @@ export const spec = { if (!serverResponse || serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } - utils.logError(errorMessage); + logError(errorMessage); return bids; } @@ -166,9 +169,9 @@ export const spec = { }, transformBidParams: function(params, isOpenRtb) { - params = utils.convertTypes({ + params = convertTypes({ 'placementId': 'number', - 'keywords': utils.transformBidderParamKeywords + 'keywords': transformBidderParamKeywords }, params); if (isOpenRtb) { @@ -180,7 +183,7 @@ export const spec = { } Object.keys(params).forEach(paramKey => { - let convertedKey = utils.convertCamelToUnderscore(paramKey); + let convertedKey = convertCamelToUnderscore(paramKey); if (convertedKey !== paramKey) { params[convertedKey] = params[paramKey]; delete params[paramKey]; @@ -193,7 +196,7 @@ export const spec = { } function isPopulatedArray(arr) { - return !!(utils.isArray(arr) && arr.length > 0); + return !!(isArray(arr) && arr.length > 0); } function deleteValues(keyPairObj) { @@ -206,9 +209,9 @@ function formatRequest(payload, bidderRequest) { let request = []; if (payload.tags.length > MAX_IMPS_PER_REQUEST) { - const clonedPayload = utils.deepClone(payload); + const clonedPayload = deepClone(payload); - utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { clonedPayload.tags = tags; const payloadString = JSON.stringify(clonedPayload); request.push({ @@ -243,14 +246,14 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } renderer.setEventHandlers({ - impression: () => utils.logMessage('AdRelevantis outstream video impression event'), - loaded: () => utils.logMessage('AdRelevantis outstream video loaded event'), + impression: () => logMessage('AdRelevantis outstream video impression event'), + loaded: () => logMessage('AdRelevantis outstream video loaded event'), ended: () => { - utils.logMessage('AdRelevantis outstream renderer video event'); + logMessage('AdRelevantis outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); @@ -295,7 +298,7 @@ function handleOutstreamRendererEvents(bid, id, eventName) { * @return Bid */ function newBid(serverBid, rtbBid, bidderRequest) { - const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); + const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]); const bid = { requestId: serverBid.uuid, cpm: rtbBid.cpm, @@ -324,7 +327,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { ttl: 3600 }); - const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); switch (videoContext) { case OUTSTREAM: bid.adResponse = serverBid; @@ -334,7 +337,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (rtbBid.renderer_url) { const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); - const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); + const rendererOptions = deepAccess(videoBid, 'renderer.options'); bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); } break; @@ -354,7 +357,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (jsTrackers == undefined) { jsTrackers = jsTrackerDisarmed; - } else if (utils.isStr(jsTrackers)) { + } else if (isStr(jsTrackers)) { jsTrackers = [jsTrackers, jsTrackerDisarmed]; } else { jsTrackers.push(jsTrackerDisarmed); @@ -402,10 +405,10 @@ function newBid(serverBid, rtbBid, bidderRequest) { }); try { const url = rtbBid.rtb.trackers[0].impression_urls[0]; - const tracker = utils.createTrackPixelHtml(url); + const tracker = createTrackPixelHtml(url); bid.ad += tracker; } catch (error) { - utils.logError('Error appending tracking pixel', error); + logError('Error appending tracking pixel', error); } } @@ -449,8 +452,8 @@ function bidToTag(bid) { if (bid.params.externalImpId) { tag.external_imp_id = bid.params.externalImpId; } - if (!utils.isEmpty(bid.params.keywords)) { - let keywords = utils.transformBidderParamKeywords(bid.params.keywords); + if (!isEmpty(bid.params.keywords)) { + let keywords = transformBidderParamKeywords(bid.params.keywords); if (keywords.length > 0) { keywords.forEach(deleteValues); @@ -461,7 +464,7 @@ function bidToTag(bid) { tag.category = bid.params.category; } - if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { + if (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`)) { tag.ad_types.push(NATIVE); if (tag.sizes.length === 0) { tag.sizes = transformSizes([1, 1]); @@ -473,8 +476,8 @@ function bidToTag(bid) { } } - const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = deepAccess(bid, 'mediaTypes.video.context'); tag.hb_source = 1; if (bid.mediaType === VIDEO || videoMediaType) { @@ -499,7 +502,7 @@ function bidToTag(bid) { } if ( - (utils.isEmpty(bid.mediaType) && utils.isEmpty(bid.mediaTypes)) || + (isEmpty(bid.mediaType) && isEmpty(bid.mediaTypes)) || (bid.mediaType === BANNER || (bid.mediaTypes && bid.mediaTypes[BANNER])) ) { tag.ad_types.push(BANNER); @@ -513,8 +516,8 @@ function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; - if (utils.isArray(requestSizes) && requestSizes.length === 2 && - !utils.isArray(requestSizes[0])) { + if (isArray(requestSizes) && requestSizes.length === 2 && + !isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); @@ -575,7 +578,7 @@ function buildNativeRequest(params) { const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); if (isImageAsset && request[requestKey].sizes) { let sizes = request[requestKey].sizes; - if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { + if (isArrayOfNums(sizes) || (isArray(sizes) && sizes.length > 0 && sizes.every(sz => isArrayOfNums(sz)))) { request[requestKey].sizes = transformSizes(request[requestKey].sizes); } } From faf00c7643d069e325212e9f63aeb3c906208b71 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 11:10:13 -0700 Subject: [PATCH 19/84] Multiple Bid/Analytics Adapters : import utils functions as needed, not whole module (#7469) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils as needed; dont import all * import utils as needed; dont import all --- modules/33acrossBidAdapter.js | 43 ++++--- modules/a4gBidAdapter.js | 6 +- modules/ablidaBidAdapter.js | 4 +- modules/adagioAnalyticsAdapter.js | 8 +- modules/adagioBidAdapter.js | 167 +++++++++++++------------ modules/adbookpspBidAdapter.js | 110 ++++++++-------- modules/adfBidAdapter.js | 30 ++--- modules/adgenerationBidAdapter.js | 30 ++--- modules/adkernelAdnAnalyticsAdapter.js | 12 +- modules/adkernelAdnBidAdapter.js | 46 +++---- 10 files changed, 232 insertions(+), 224 deletions(-) diff --git a/modules/33acrossBidAdapter.js b/modules/33acrossBidAdapter.js index 4b8028d97fd..2bdbdd6414b 100644 --- a/modules/33acrossBidAdapter.js +++ b/modules/33acrossBidAdapter.js @@ -1,6 +1,9 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; +import { + deepAccess, uniques, isArray, getWindowTop, isGptPubadsDefined, isSlotMatchingAdUnitCode, logInfo, logWarn, + getWindowSelf +} from '../src/utils.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; const BIDDER_CODE = '33across'; @@ -61,7 +64,7 @@ function _validateBasic(bid) { } function _validateGUID(bid) { - const siteID = utils.deepAccess(bid, 'params.siteId', '') || ''; + const siteID = deepAccess(bid, 'params.siteId', '') || ''; if (siteID.trim().match(GUID_PATTERN) === null) { return false; } @@ -70,7 +73,7 @@ function _validateGUID(bid) { } function _validateBanner(bid) { - const banner = utils.deepAccess(bid, 'mediaTypes.banner'); + const banner = deepAccess(bid, 'mediaTypes.banner'); // If there's no banner no need to validate against banner rules if (banner === undefined) { return true; @@ -84,8 +87,8 @@ function _validateBanner(bid) { } function _validateVideo(bid) { - const videoAdUnit = utils.deepAccess(bid, 'mediaTypes.video'); - const videoBidderParams = utils.deepAccess(bid, 'params.video', {}); + const videoAdUnit = deepAccess(bid, 'mediaTypes.video'); + const videoBidderParams = deepAccess(bid, 'params.video', {}); // If there's no video no need to validate against video rules if (videoAdUnit === undefined) { @@ -145,7 +148,7 @@ function buildRequests(bidRequests, bidderRequest) { const uspConsent = bidderRequest && bidderRequest.uspConsent; const pageUrl = (bidderRequest && bidderRequest.refererInfo) ? (bidderRequest.refererInfo.referer) : (undefined); - adapterState.uniqueSiteIds = bidRequests.map(req => req.params.siteId).filter(utils.uniques); + adapterState.uniqueSiteIds = bidRequests.map(req => req.params.siteId).filter(uniques); return bidRequests.map(bidRequest => _createServerRequest( { @@ -168,13 +171,13 @@ function _createServerRequest({bidRequest, gdprConsent = {}, uspConsent, pageUrl */ ttxRequest.imp = [{}]; - if (utils.deepAccess(bidRequest, 'mediaTypes.banner')) { + if (deepAccess(bidRequest, 'mediaTypes.banner')) { ttxRequest.imp[0].banner = { ..._buildBannerORTB(bidRequest) } } - if (utils.deepAccess(bidRequest, 'mediaTypes.video')) { + if (deepAccess(bidRequest, 'mediaTypes.video')) { ttxRequest.imp[0].video = _buildVideoORTB(bidRequest); } @@ -279,7 +282,7 @@ function setExtension(obj = {}, key, value) { // BUILD REQUESTS: SIZE INFERENCE function _transformSizes(sizes) { - if (utils.isArray(sizes) && sizes.length === 2 && !utils.isArray(sizes[0])) { + if (isArray(sizes) && sizes.length === 2 && !isArray(sizes[0])) { return [ _getSize(sizes) ]; } @@ -308,7 +311,7 @@ function _getProduct(bidRequest) { // BUILD REQUESTS: BANNER function _buildBannerORTB(bidRequest) { - const bannerAdUnit = utils.deepAccess(bidRequest, 'mediaTypes.banner', {}); + const bannerAdUnit = deepAccess(bidRequest, 'mediaTypes.banner', {}); const element = _getAdSlotHTMLElement(bidRequest.adUnitCode); const sizes = _transformSizes(bannerAdUnit.sizes); @@ -340,7 +343,7 @@ function _buildBannerORTB(bidRequest) { const minSize = _getMinSize(sizes); const viewabilityAmount = _isViewabilityMeasurable(element) - ? _getViewability(element, utils.getWindowTop(), minSize) + ? _getViewability(element, getWindowTop(), minSize) : NON_MEASURABLE; const ext = contributeViewability(viewabilityAmount); @@ -354,8 +357,8 @@ function _buildBannerORTB(bidRequest) { // BUILD REQUESTS: VIDEO // eslint-disable-next-line no-unused-vars function _buildVideoORTB(bidRequest) { - const videoAdUnit = utils.deepAccess(bidRequest, 'mediaTypes.video', {}); - const videoBidderParams = utils.deepAccess(bidRequest, 'params.video', {}); + const videoAdUnit = deepAccess(bidRequest, 'mediaTypes.video', {}); + const videoBidderParams = deepAccess(bidRequest, 'params.video', {}); const videoParams = { ...videoAdUnit, @@ -429,23 +432,23 @@ function _getViewability(element, topWin, { w, h } = {}) { } function _mapAdUnitPathToElementId(adUnitCode) { - if (utils.isGptPubadsDefined()) { + if (isGptPubadsDefined()) { // eslint-disable-next-line no-undef const adSlots = googletag.pubads().getSlots(); - const isMatchingAdSlot = utils.isSlotMatchingAdUnitCode(adUnitCode); + const isMatchingAdSlot = isSlotMatchingAdUnitCode(adUnitCode); for (let i = 0; i < adSlots.length; i++) { if (isMatchingAdSlot(adSlots[i])) { const id = adSlots[i].getSlotElementId(); - utils.logInfo(`[33Across Adapter] Map ad unit path to HTML element id: '${adUnitCode}' -> ${id}`); + logInfo(`[33Across Adapter] Map ad unit path to HTML element id: '${adUnitCode}' -> ${id}`); return id; } } } - utils.logWarn(`[33Across Adapter] Unable to locate element for ad unit code: '${adUnitCode}'`); + logWarn(`[33Across Adapter] Unable to locate element for ad unit code: '${adUnitCode}'`); return null; } @@ -546,7 +549,7 @@ function contributeViewability(viewabilityAmount) { function _isIframe() { try { - return utils.getWindowSelf() !== utils.getWindowTop(); + return getWindowSelf() !== getWindowTop(); } catch (e) { return true; } @@ -579,7 +582,7 @@ function _createBidResponse(response) { ad: response.seatbid[0].bid[0].adm, ttl: response.seatbid[0].bid[0].ttl || 60, creativeId: response.seatbid[0].bid[0].crid, - mediaType: utils.deepAccess(response.seatbid[0].bid[0], 'ext.ttx.mediaType', BANNER), + mediaType: deepAccess(response.seatbid[0].bid[0], 'ext.ttx.mediaType', BANNER), currency: response.cur, netRevenue: true } @@ -591,7 +594,7 @@ function _createBidResponse(response) { } if (bid.mediaType === VIDEO) { - const vastType = utils.deepAccess(response.seatbid[0].bid[0], 'ext.ttx.vastType', 'xml'); + const vastType = deepAccess(response.seatbid[0].bid[0], 'ext.ttx.vastType', 'xml'); if (vastType === 'xml') { bid.vastXml = bid.ad; diff --git a/modules/a4gBidAdapter.js b/modules/a4gBidAdapter.js index 01c59616dc0..03f9d6fd726 100644 --- a/modules/a4gBidAdapter.js +++ b/modules/a4gBidAdapter.js @@ -1,5 +1,5 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; +import { _each } from '../src/utils.js'; const A4G_BIDDER_CODE = 'a4g'; const A4G_CURRENCY = 'USD'; @@ -28,7 +28,7 @@ export const spec = { const sizeParams = []; const zoneIds = []; - utils._each(validBidRequests, function(bid) { + _each(validBidRequests, function(bid) { if (!deliveryUrl && typeof bid.params.deliveryUrl === 'string') { deliveryUrl = bid.params.deliveryUrl; } @@ -66,7 +66,7 @@ export const spec = { interpretResponse: function(serverResponses, request) { const bidResponses = []; - utils._each(serverResponses.body, function(response) { + _each(serverResponses.body, function(response) { if (response.cpm > 0) { const bidResponse = { requestId: response.id, diff --git a/modules/ablidaBidAdapter.js b/modules/ablidaBidAdapter.js index 2400952367f..cb4f4ef2724 100644 --- a/modules/ablidaBidAdapter.js +++ b/modules/ablidaBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { triggerPixel } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; @@ -79,7 +79,7 @@ export const spec = { }, onBidWon: function (bid) { if (!bid['nurl']) { return; } - utils.triggerPixel(bid['nurl']); + triggerPixel(bid['nurl']); } }; diff --git a/modules/adagioAnalyticsAdapter.js b/modules/adagioAnalyticsAdapter.js index fd7a742d9e7..f929f7e660b 100644 --- a/modules/adagioAnalyticsAdapter.js +++ b/modules/adagioAnalyticsAdapter.js @@ -5,7 +5,7 @@ import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; +import { getWindowTop } from '../src/utils.js'; const emptyUrl = ''; const analyticsType = 'endpoint'; @@ -13,12 +13,12 @@ const events = Object.keys(CONSTANTS.EVENTS).map(key => CONSTANTS.EVENTS[key]); const VERSION = '2.0.0'; const adagioEnqueue = function adagioEnqueue(action, data) { - utils.getWindowTop().ADAGIO.queue.push({ action, data, ts: Date.now() }); + getWindowTop().ADAGIO.queue.push({ action, data, ts: Date.now() }); } function canAccessTopWindow() { try { - if (utils.getWindowTop().location.href) { + if (getWindowTop().location.href) { return true; } } catch (error) { @@ -41,7 +41,7 @@ adagioAdapter.enableAnalytics = config => { return; } - const w = utils.getWindowTop(); + const w = getWindowTop(); w.ADAGIO = w.ADAGIO || {}; w.ADAGIO.queue = w.ADAGIO.queue || []; diff --git a/modules/adagioBidAdapter.js b/modules/adagioBidAdapter.js index ffa955290be..264cf5f9fcb 100644 --- a/modules/adagioBidAdapter.js +++ b/modules/adagioBidAdapter.js @@ -1,5 +1,8 @@ import find from 'core-js-pure/features/array/find.js'; -import * as utils from '../src/utils.js'; +import { + isInteger, isArray, deepAccess, mergeDeep, logWarn, logInfo, logError, getWindowTop, getWindowSelf, generateUUID, _map, + getDNT, parseUrl, getUniqueIdentifierStr, isNumber, cleanObj, isFn, inIframe, deepClone, getGptSlotInfoForAdUnitCode +} from '../src/utils.js'; import { config } from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { loadExternalScript } from '../src/adloader.js'; @@ -31,22 +34,22 @@ const DEFAULT_FLOOR = 0.1; // https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf export const ORTB_VIDEO_PARAMS = { 'mimes': (value) => Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string'), - 'minduration': (value) => utils.isInteger(value), - 'maxduration': (value) => utils.isInteger(value), + 'minduration': (value) => isInteger(value), + 'maxduration': (value) => isInteger(value), 'protocols': (value) => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].indexOf(v) !== -1), - 'w': (value) => utils.isInteger(value), - 'h': (value) => utils.isInteger(value), - 'startdelay': (value) => utils.isInteger(value), + 'w': (value) => isInteger(value), + 'h': (value) => isInteger(value), + 'startdelay': (value) => isInteger(value), 'placement': (value) => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5].indexOf(v) !== -1), 'linearity': (value) => [1, 2].indexOf(value) !== -1, 'skip': (value) => [0, 1].indexOf(value) !== -1, - 'skipmin': (value) => utils.isInteger(value), - 'skipafter': (value) => utils.isInteger(value), - 'sequence': (value) => utils.isInteger(value), + 'skipmin': (value) => isInteger(value), + 'skipafter': (value) => isInteger(value), + 'sequence': (value) => isInteger(value), 'battr': (value) => Array.isArray(value) && value.every(v => Array.from({length: 17}, (_, i) => i + 1).indexOf(v) !== -1), - 'maxextended': (value) => utils.isInteger(value), - 'minbitrate': (value) => utils.isInteger(value), - 'maxbitrate': (value) => utils.isInteger(value), + 'maxextended': (value) => isInteger(value), + 'minbitrate': (value) => isInteger(value), + 'maxbitrate': (value) => isInteger(value), 'boxingallowed': (value) => [0, 1].indexOf(value) !== -1, 'playbackmethod': (value) => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5, 6].indexOf(v) !== -1), 'playbackend': (value) => [1, 2, 3].indexOf(value) !== -1, @@ -88,7 +91,7 @@ export const GlobalExchange = (function() { return value; } }); - let random = utils.deepAccess(adagioStorage, 'session.rnd'); + let random = deepAccess(adagioStorage, 'session.rnd'); let newSession = false; if (internal.isNewSession(adagioStorage)) { @@ -103,7 +106,7 @@ export const GlobalExchange = (function() { } } - utils.mergeDeep(exchangeData, adagioStorage, data); + mergeDeep(exchangeData, adagioStorage, data); internal.enqueue({ action: 'session', @@ -121,14 +124,14 @@ export const GlobalExchange = (function() { export function adagioScriptFromLocalStorageCb(ls) { try { if (!ls) { - utils.logWarn(`${LOG_PREFIX} script not found.`); + logWarn(`${LOG_PREFIX} script not found.`); return; } const hashRgx = /^(\/\/ hash: (.+)\n)(.+\n)$/; if (!hashRgx.test(ls)) { - utils.logWarn(`${LOG_PREFIX} no hash found.`); + logWarn(`${LOG_PREFIX} no hash found.`); storage.removeDataFromLocalStorage(ADAGIO_LOCALSTORAGE_KEY); } else { const r = ls.match(hashRgx); @@ -136,15 +139,15 @@ export function adagioScriptFromLocalStorageCb(ls) { const content = r[3]; if (verify(content, hash, ADAGIO_PUBKEY, ADAGIO_PUBKEY_E)) { - utils.logInfo(`${LOG_PREFIX} start script.`); + logInfo(`${LOG_PREFIX} start script.`); Function(ls)(); // eslint-disable-line no-new-func } else { - utils.logWarn(`${LOG_PREFIX} invalid script found.`); + logWarn(`${LOG_PREFIX} invalid script found.`); storage.removeDataFromLocalStorage(ADAGIO_LOCALSTORAGE_KEY); } } } catch (err) { - utils.logError(LOG_PREFIX, err); + logError(LOG_PREFIX, err); } } @@ -167,7 +170,7 @@ export function getAdagioScript() { // This key is removed only if localStorage is not accessible. window.localStorage.removeItem('adagio'); } catch (e) { - utils.logInfo(`${LOG_PREFIX} unable to clear Adagio scripts from localstorage.`); + logInfo(`${LOG_PREFIX} unable to clear Adagio scripts from localstorage.`); } } }); @@ -175,7 +178,7 @@ export function getAdagioScript() { function canAccessTopWindow() { try { - if (utils.getWindowTop().location.href) { + if (getWindowTop().location.href) { return true; } } catch (error) { @@ -184,17 +187,17 @@ function canAccessTopWindow() { } function getCurrentWindow() { - return currentWindow || utils.getWindowSelf(); + return currentWindow || getWindowSelf(); } function isSafeFrameWindow() { - const ws = utils.getWindowSelf(); + const ws = getWindowSelf(); return !!(ws.$sf && ws.$sf.ext); } function initAdagio() { if (canAccessTopWindow()) { - currentWindow = (canAccessTopWindow()) ? utils.getWindowTop() : utils.getWindowSelf(); + currentWindow = (canAccessTopWindow()) ? getWindowTop() : getWindowSelf(); } const w = internal.getCurrentWindow(); @@ -211,7 +214,7 @@ function initAdagio() { try { GlobalExchange.prepareExchangeData(storageData); } catch (e) { - utils.logError(LOG_PREFIX, e); + logError(LOG_PREFIX, e); } }); @@ -230,7 +233,7 @@ function getPageviewId() { const w = internal.getCurrentWindow(); w.ADAGIO = w.ADAGIO || {}; - w.ADAGIO.pageviewId = w.ADAGIO.pageviewId || utils.generateUUID(); + w.ADAGIO.pageviewId = w.ADAGIO.pageviewId || generateUUID(); return w.ADAGIO.pageviewId; }; @@ -240,7 +243,7 @@ function getDevice() { return { userAgent: navigator.userAgent, language: navigator[language], - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, geo: {}, js: 1 }; @@ -254,12 +257,12 @@ function getSite(bidderRequest) { const { refererInfo } = bidderRequest; if (canAccessTopWindow()) { - const wt = utils.getWindowTop(); + const wt = getWindowTop(); domain = wt.location.hostname; page = wt.location.href; referrer = wt.document.referrer || ''; } else if (refererInfo.reachedTop) { - const url = utils.parseUrl(refererInfo.referer); + const url = parseUrl(refererInfo.referer); domain = url.hostname; page = refererInfo.referer; } else if (refererInfo.stack && refererInfo.stack.length && refererInfo.stack[0]) { @@ -267,7 +270,7 @@ function getSite(bidderRequest) { // will be considered as "localhost" by the parseUrl function. // As the isBidRequestValid returns false when it does not reach the referer // this should never called. - const url = utils.parseUrl(refererInfo.stack[0]); + const url = parseUrl(refererInfo.stack[0]); domain = url.hostname; } @@ -280,9 +283,9 @@ function getSite(bidderRequest) { function getElementFromTopWindow(element, currentWindow) { try { - if (utils.getWindowTop() === currentWindow) { + if (getWindowTop() === currentWindow) { if (!element.getAttribute('id')) { - element.setAttribute('id', `adg-${utils.getUniqueIdentifierStr()}`); + element.setAttribute('id', `adg-${getUniqueIdentifierStr()}`); } return element; } else { @@ -297,13 +300,13 @@ function getElementFromTopWindow(element, currentWindow) { return getElementFromTopWindow(frame, currentWindow.parent); } } catch (err) { - utils.logWarn(`${LOG_PREFIX}`, err); + logWarn(`${LOG_PREFIX}`, err); return false; } }; function autoDetectAdUnitElementIdFromGpt(adUnitCode) { - const autoDetectedAdUnit = utils.getGptSlotInfoForAdUnitCode(adUnitCode); + const autoDetectedAdUnit = getGptSlotInfoForAdUnitCode(adUnitCode); if (autoDetectedAdUnit && autoDetectedAdUnit.divId) { return autoDetectedAdUnit.divId; @@ -312,11 +315,11 @@ function autoDetectAdUnitElementIdFromGpt(adUnitCode) { function isRendererPreferredFromPublisher(bidRequest) { // renderer defined at adUnit level - const adUnitRenderer = utils.deepAccess(bidRequest, 'renderer'); + const adUnitRenderer = deepAccess(bidRequest, 'renderer'); const hasValidAdUnitRenderer = !!(adUnitRenderer && adUnitRenderer.url && adUnitRenderer.render); // renderer defined at adUnit.mediaTypes level - const mediaTypeRenderer = utils.deepAccess(bidRequest, 'mediaTypes.video.renderer'); + const mediaTypeRenderer = deepAccess(bidRequest, 'mediaTypes.video.renderer'); const hasValidMediaTypeRenderer = !!(mediaTypeRenderer && mediaTypeRenderer.url && mediaTypeRenderer.render); return !!( @@ -332,10 +335,10 @@ function isRendererPreferredFromPublisher(bidRequest) { */ function isNewSession(adagioStorage) { const now = Date.now(); - const { lastActivityTime, vwSmplg } = utils.deepAccess(adagioStorage, 'session', {}); + const { lastActivityTime, vwSmplg } = deepAccess(adagioStorage, 'session', {}); return ( - !utils.isNumber(lastActivityTime) || - !utils.isNumber(vwSmplg) || + !isNumber(lastActivityTime) || + !isNumber(vwSmplg) || (now - lastActivityTime) > MAX_SESS_DURATION ) } @@ -344,7 +347,7 @@ function setPlayerName(bidRequest) { const playerName = (internal.isRendererPreferredFromPublisher(bidRequest)) ? 'other' : 'adagio'; if (playerName === 'other') { - utils.logWarn(`${LOG_PREFIX} renderer.backupOnly has not been set. Adagio recommends to use its own player to get expected behavior.`); + logWarn(`${LOG_PREFIX} renderer.backupOnly has not been set. Adagio recommends to use its own player to get expected behavior.`); } return playerName; @@ -365,7 +368,7 @@ export const internal = { }; function _getGdprConsent(bidderRequest) { - if (!utils.deepAccess(bidderRequest, 'gdprConsent')) { + if (!deepAccess(bidderRequest, 'gdprConsent')) { return false; } @@ -376,7 +379,7 @@ function _getGdprConsent(bidderRequest) { allowAuctionWithoutConsent } = bidderRequest.gdprConsent; - return utils.cleanObj({ + return cleanObj({ apiVersion, consentString, consentRequired: gdprApplies ? 1 : 0, @@ -391,22 +394,22 @@ function _getCoppa() { } function _getUspConsent(bidderRequest) { - return (utils.deepAccess(bidderRequest, 'uspConsent')) ? { uspConsent: bidderRequest.uspConsent } : false; + return (deepAccess(bidderRequest, 'uspConsent')) ? { uspConsent: bidderRequest.uspConsent } : false; } function _getSchain(bidRequest) { - return utils.deepAccess(bidRequest, 'schain'); + return deepAccess(bidRequest, 'schain'); } function _getEids(bidRequest) { - if (utils.deepAccess(bidRequest, 'userId')) { + if (deepAccess(bidRequest, 'userId')) { return createEidsArray(bidRequest.userId); } } function _buildVideoBidRequest(bidRequest) { - const videoAdUnitParams = utils.deepAccess(bidRequest, 'mediaTypes.video', {}); - const videoBidderParams = utils.deepAccess(bidRequest, 'params.video', {}); + const videoAdUnitParams = deepAccess(bidRequest, 'mediaTypes.video', {}); + const videoBidderParams = deepAccess(bidRequest, 'params.video', {}); const computedParams = {}; // Special case for playerSize. @@ -436,7 +439,7 @@ function _buildVideoBidRequest(bidRequest) { bidRequest.mediaTypes.video[paramName] = videoParams[paramName]; } else { delete bidRequest.mediaTypes.video[paramName]; - utils.logWarn(`${LOG_PREFIX} The OpenRTB video param ${paramName} has been skipped due to misformating. Please refer to OpenRTB 2.5 spec.`); + logWarn(`${LOG_PREFIX} The OpenRTB video param ${paramName} has been skipped due to misformating. Please refer to OpenRTB 2.5 spec.`); } } }); @@ -447,14 +450,14 @@ function _renderer(bid) { if (typeof window.ADAGIO.outstreamPlayer === 'function') { window.ADAGIO.outstreamPlayer(bid); } else { - utils.logError(`${LOG_PREFIX} Adagio outstream player is not defined`); + logError(`${LOG_PREFIX} Adagio outstream player is not defined`); } }); } function _parseNativeBidResponse(bid) { if (!bid.admNative || !Array.isArray(bid.admNative.assets)) { - utils.logError(`${LOG_PREFIX} Invalid native response`); + logError(`${LOG_PREFIX} Invalid native response`); return; } @@ -559,7 +562,7 @@ function _parseNativeBidResponse(bid) { } function _getFloors(bidRequest) { - if (!utils.isFn(bidRequest.getFloor)) { + if (!isFn(bidRequest.getFloor)) { return false; } @@ -572,9 +575,9 @@ function _getFloors(bidRequest) { size: [] }); - floors.push(utils.cleanObj({ + floors.push(cleanObj({ mt: mediaType, - s: utils.isArray(size) ? `${size[0]}x${size[1]}` : undefined, + s: isArray(size) ? `${size[0]}x${size[1]}` : undefined, f: (!isNaN(info.floor) && info.currency === CURRENCY) ? info.floor : DEFAULT_FLOOR })); } @@ -584,7 +587,7 @@ function _getFloors(bidRequest) { const sizeProp = mediaType === VIDEO ? 'playerSize' : 'sizes'; if (bidRequest.mediaTypes[mediaType][sizeProp] && bidRequest.mediaTypes[mediaType][sizeProp].length) { - if (utils.isArray(bidRequest.mediaTypes[mediaType][sizeProp][0])) { + if (isArray(bidRequest.mediaTypes[mediaType][sizeProp][0])) { bidRequest.mediaTypes[mediaType][sizeProp].forEach(size => { getAndPush(mediaType, [size[0], size[1]]); }); @@ -621,7 +624,7 @@ export function setExtraParam(bid, paramName) { const adgGlobalConf = config.getConfig('adagio') || {}; const ortb2Conf = config.getConfig('ortb2'); - const detected = adgGlobalConf[paramName] || utils.deepAccess(ortb2Conf, `site.ext.data.${paramName}`, null); + const detected = adgGlobalConf[paramName] || deepAccess(ortb2Conf, `site.ext.data.${paramName}`, null); if (detected) { bid.params[paramName] = detected; } @@ -644,7 +647,7 @@ function autoFillParams(bid) { bid.params.placement = bid.adUnitCode; } - bid.params.adUnitElementId = utils.deepAccess(bid, 'ortb2Imp.ext.data.elementId', null) || bid.params.adUnitElementId; + bid.params.adUnitElementId = deepAccess(bid, 'ortb2Imp.ext.data.elementId', null) || bid.params.adUnitElementId; if (!bid.params.adUnitElementId) { if (adgGlobalConf.useAdUnitCodeAsAdUnitElementId === true || bid.params.useAdUnitCodeAsAdUnitElementId === true) { @@ -667,7 +670,7 @@ function getPageDimensions() { } // the page dimension can be computed on window.top only. - const wt = utils.getWindowTop(); + const wt = getWindowTop(); const body = wt.document.querySelector('body'); if (!body) { @@ -692,17 +695,17 @@ function getViewPortDimensions() { const viewportDims = { w: 0, h: 0 }; if (isSafeFrameWindow()) { - const ws = utils.getWindowSelf(); + const ws = getWindowSelf(); if (typeof ws.$sf.ext.geom !== 'function') { - utils.logWarn(LOG_PREFIX, 'Unable to compute from safeframe api.'); + logWarn(LOG_PREFIX, 'Unable to compute from safeframe api.'); return ''; } const sfGeom = ws.$sf.ext.geom(); if (!sfGeom || !sfGeom.win) { - utils.logWarn(LOG_PREFIX, 'Unable to compute from safeframe api. Missing `geom().win` property'); + logWarn(LOG_PREFIX, 'Unable to compute from safeframe api. Missing `geom().win` property'); return ''; } @@ -710,7 +713,7 @@ function getViewPortDimensions() { viewportDims.h = Math.round(sfGeom.h); } else { // window.top based computing - const wt = utils.getWindowTop(); + const wt = getWindowTop(); viewportDims.w = wt.innerWidth; viewportDims.h = wt.innerHeight; } @@ -730,17 +733,17 @@ function getSlotPosition(adUnitElementId) { const position = { x: 0, y: 0 }; if (isSafeFrameWindow()) { - const ws = utils.getWindowSelf(); + const ws = getWindowSelf(); if (typeof ws.$sf.ext.geom !== 'function') { - utils.logWarn(LOG_PREFIX, 'Unable to compute from safeframe api.'); + logWarn(LOG_PREFIX, 'Unable to compute from safeframe api.'); return ''; } const sfGeom = ws.$sf.ext.geom(); if (!sfGeom || !sfGeom.self) { - utils.logWarn(LOG_PREFIX, 'Unable to compute from safeframe api. Missing `geom().self` property'); + logWarn(LOG_PREFIX, 'Unable to compute from safeframe api. Missing `geom().self` property'); return ''; } @@ -748,13 +751,13 @@ function getSlotPosition(adUnitElementId) { position.y = Math.round(sfGeom.l); } else if (canAccessTopWindow()) { // window.top based computing - const wt = utils.getWindowTop(); + const wt = getWindowTop(); const d = wt.document; let domElement; - if (utils.inIframe() === true) { - const ws = utils.getWindowSelf(); + if (inIframe() === true) { + const ws = getWindowSelf(); const currentElement = ws.document.getElementById(adUnitElementId); domElement = internal.getElementFromTopWindow(currentElement, ws); } else { @@ -813,7 +816,7 @@ function getDomLoadingDuration() { let domLoadingDuration = -1; let performance; - performance = (canAccessTopWindow()) ? utils.getWindowTop().performance : utils.getWindowSelf().performance; + performance = (canAccessTopWindow()) ? getWindowTop().performance : getWindowSelf().performance; if (performance && performance.timing && performance.timing.navigationStart > 0) { const val = performance.timing.domLoading - performance.timing.navigationStart; @@ -871,13 +874,13 @@ export const spec = { autoFillParams(bid); if (!internal.getRefererInfo().reachedTop) { - utils.logWarn(`${LOG_PREFIX} the main page url is unreachabled.`); + logWarn(`${LOG_PREFIX} the main page url is unreachabled.`); // internal.enqueue(debugData()); return false; } if (!(bid.params.organizationId && bid.params.site && bid.params.placement)) { - utils.logWarn(`${LOG_PREFIX} at least one required param is missing.`); + logWarn(`${LOG_PREFIX} at least one required param is missing.`); // internal.enqueue(debugData()); return false; } @@ -896,7 +899,7 @@ export const spec = { const schain = _getSchain(validBidRequests[0]); const eids = _getEids(validBidRequests[0]) || []; - const adUnits = utils._map(validBidRequests, (bidRequest) => { + const adUnits = _map(validBidRequests, (bidRequest) => { const globalFeatures = GlobalExchange.getOrSetGlobalFeatures(); const features = { ...globalFeatures, @@ -925,7 +928,7 @@ export const spec = { // Handle priceFloors module bidRequest.floors = _getFloors(bidRequest); - if (utils.deepAccess(bidRequest, 'mediaTypes.video')) { + if (deepAccess(bidRequest, 'mediaTypes.video')) { _buildVideoBidRequest(bidRequest); } @@ -936,7 +939,7 @@ export const spec = { // Group ad units by organizationId const groupedAdUnits = adUnits.reduce((groupedAdUnits, adUnit) => { - const adUnitCopy = utils.deepClone(adUnit); + const adUnitCopy = deepClone(adUnit); adUnitCopy.params.organizationId = adUnitCopy.params.organizationId.toString(); // remove useless props @@ -950,12 +953,12 @@ export const spec = { }, {}); // Build one request per organizationId - const requests = utils._map(Object.keys(groupedAdUnits), organizationId => { + const requests = _map(Object.keys(groupedAdUnits), organizationId => { return { method: 'POST', url: ENDPOINT, data: { - id: utils.generateUUID(), + id: generateUUID(), organizationId: organizationId, secure: secure, device: device, @@ -1001,12 +1004,12 @@ export const spec = { const bidReq = (find(bidRequest.data.adUnits, bid => bid.bidId === bidObj.requestId)); if (bidReq) { - bidObj.meta = utils.deepAccess(bidObj, 'meta', {}); + bidObj.meta = deepAccess(bidObj, 'meta', {}); bidObj.meta.mediaType = bidObj.mediaType; bidObj.meta.advertiserDomains = (Array.isArray(bidObj.aDomain) && bidObj.aDomain.length) ? bidObj.aDomain : []; if (bidObj.mediaType === VIDEO) { - const mediaTypeContext = utils.deepAccess(bidReq, 'mediaTypes.video.context'); + const mediaTypeContext = deepAccess(bidReq, 'mediaTypes.video.context'); // Adagio SSP returns a `vastXml` only. No `vastUrl` nor `videoCacheKey`. if (!bidObj.vastUrl && bidObj.vastXml) { bidObj.vastUrl = 'data:text/xml;charset=utf-8;base64,' + btoa(bidObj.vastXml.replace(/\\"/g, '"')); @@ -1018,8 +1021,8 @@ export const spec = { adUnitCode: bidObj.adUnitCode, url: bidObj.urlRenderer || RENDERER_URL, config: { - ...utils.deepAccess(bidReq, 'mediaTypes.video'), - ...utils.deepAccess(bidObj, 'outstream', {}) + ...deepAccess(bidReq, 'mediaTypes.video'), + ...deepAccess(bidObj, 'outstream', {}) } }); @@ -1043,7 +1046,7 @@ export const spec = { } } } catch (err) { - utils.logError(err); + logError(err); } return bidResponses; }, @@ -1077,7 +1080,7 @@ export const spec = { if (isOrtb) { autoFillParams(adagioBid); - adagioBid.params.auctionId = utils.deepAccess(adagioBidderRequest, 'auctionId'); + adagioBid.params.auctionId = deepAccess(adagioBidderRequest, 'auctionId'); const globalFeatures = GlobalExchange.getOrSetGlobalFeatures(); adagioBid.params.features = { @@ -1090,7 +1093,7 @@ export const spec = { adagioBid.params.prebidVersion = '$prebid.version$'; adagioBid.params.data = GlobalExchange.getExchangeData(); - if (utils.deepAccess(adagioBid, 'mediaTypes.video.context') === OUTSTREAM) { + if (deepAccess(adagioBid, 'mediaTypes.video.context') === OUTSTREAM) { adagioBid.params.playerName = setPlayerName(adagioBid); } diff --git a/modules/adbookpspBidAdapter.js b/modules/adbookpspBidAdapter.js index d3f3ba295b9..ca4795c574f 100644 --- a/modules/adbookpspBidAdapter.js +++ b/modules/adbookpspBidAdapter.js @@ -3,7 +3,10 @@ import find from 'core-js-pure/features/array/find'; import { config } from '../src/config.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import { getStorageManager } from '../src/storageManager.js'; -import * as utils from '../src/utils.js'; +import { + isPlainObject, deepSetValue, deepAccess, logWarn, inIframe, isNumber, logError, isArray, uniques, + flatten, triggerPixel, isStr, isEmptyStr, generateUUID +} from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; /** @@ -150,7 +153,7 @@ function buildDevice() { const deviceConfig = common.getConfig('device'); - if (utils.isPlainObject(deviceConfig)) { + if (isPlainObject(deviceConfig)) { return { ...device, ...deviceConfig }; } @@ -163,12 +166,12 @@ function buildRegs(bidderRequest) { }; if (bidderRequest.gdprConsent) { - utils.deepSetValue( + deepSetValue( regs, 'ext.gdpr', bidderRequest.gdprConsent.gdprApplies ? 1 : 0 ); - utils.deepSetValue( + deepSetValue( regs, 'ext.gdprConsentString', bidderRequest.gdprConsent.consentString || '' @@ -176,7 +179,7 @@ function buildRegs(bidderRequest) { } if (bidderRequest.uspConsent) { - utils.deepSetValue(regs, 'ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(regs, 'ext.us_privacy', bidderRequest.uspConsent); } return regs; @@ -187,10 +190,10 @@ function buildSource(bidRequests, bidderRequest) { fd: 1, tid: bidderRequest.auctionId, }; - const schain = utils.deepAccess(bidRequests, '0.schain'); + const schain = deepAccess(bidRequests, '0.schain'); if (schain) { - utils.deepSetValue(source, 'ext.schain', schain); + deepSetValue(source, 'ext.schain', schain); } return source; @@ -232,7 +235,7 @@ function buildMediaTypeObject(mediaType, bidRequest) { case VIDEO: return buildVideoObject(bidRequest); default: - utils.logWarn(`${BIDDER_CODE}: Unsupported media type ${mediaType}!`); + logWarn(`${BIDDER_CODE}: Unsupported media type ${mediaType}!`); } } @@ -246,7 +249,7 @@ function buildBannerObject(bidRequest) { return { pos: 0, - topframe: utils.inIframe() ? 0 : 1, + topframe: inIframe() ? 0 : 1, format, w, h, @@ -261,8 +264,8 @@ function buildVideoObject(bidRequest) { }; for (const param of VIDEO_PARAMS) { - const paramsValue = utils.deepAccess(bidRequest, `params.video.${param}`); - const mediaTypeValue = utils.deepAccess( + const paramsValue = deepAccess(bidRequest, `params.video.${param}`); + const mediaTypeValue = deepAccess( bidRequest, `mediaTypes.video.${param}` ); @@ -276,10 +279,10 @@ function buildVideoObject(bidRequest) { } function getVideoSize(bidRequest) { - const playerSize = utils.deepAccess(bidRequest, 'mediaTypes.video.playerSize', [[]]); - const { w, h } = utils.deepAccess(bidRequest, 'mediaTypes.video', {}); + const playerSize = deepAccess(bidRequest, 'mediaTypes.video.playerSize', [[]]); + const { w, h } = deepAccess(bidRequest, 'mediaTypes.video', {}); - if (utils.isNumber(w) && utils.isNumber(h)) { + if (isNumber(w) && isNumber(h)) { return { w, h }; } @@ -296,11 +299,11 @@ function buildImpExt(validBidRequest) { const ext = {}; if (placementId) { - utils.deepSetValue(ext, 'adbook.placementId', placementId); + deepSetValue(ext, 'adbook.placementId', placementId); } if (effectiverOrgId) { - utils.deepSetValue(ext, 'adbook.orgId', effectiverOrgId); + deepSetValue(ext, 'adbook.orgId', effectiverOrgId); } return ext; @@ -314,20 +317,19 @@ function interpretResponse(bidResponse, bidderRequest) { const bidderRequestBody = safeJSONparse(bidderRequest.data); if ( - utils.deepAccess(bidderRequestBody, 'id') != - utils.deepAccess(bidResponse, 'body.id') + deepAccess(bidderRequestBody, 'id') != + deepAccess(bidResponse, 'body.id') ) { - utils.logError( + logError( `${BIDDER_CODE}: Bid response id does not match bidder request id` ); return []; } - const referrer = utils.deepAccess(bidderRequestBody, 'site.ref', ''); - const incomingBids = utils - .deepAccess(bidResponse, 'body.seatbid', []) - .filter((seat) => utils.isArray(seat.bid)) + const referrer = deepAccess(bidderRequestBody, 'site.ref', ''); + const incomingBids = deepAccess(bidResponse, 'body.seatbid', []) + .filter((seat) => isArray(seat.bid)) .reduce((bids, seat) => bids.concat(seat.bid), []) .filter(validateBid(bidderRequestBody)); const targetingMap = buildTargetingMap(incomingBids); @@ -366,11 +368,11 @@ const impToPrebidBid = const bidRequest = findBidRequest(bidderRequestBody, bid); if (!bidRequest) { - utils.logError(`${BIDDER_CODE}: Could not match bid to bid request`); + logError(`${BIDDER_CODE}: Could not match bid to bid request`); return null; } - const categories = utils.deepAccess(bid, 'cat', []); + const categories = deepAccess(bid, 'cat', []); const mediaType = getMediaType(bid.adm); let prebidBid = { ad: bid.adm, @@ -383,7 +385,7 @@ const impToPrebidBid = creativeId: bid.crid || bid.id, currency: bidResponseCurrency || getBidderConfig('defaultCurrency'), height: bid.h, - lineItemId: utils.deepAccess(bid, 'ext.liid'), + lineItemId: deepAccess(bid, 'ext.liid'), mediaType, meta: { advertiserDomains: bid.adomain, @@ -408,7 +410,7 @@ const impToPrebidBid = return prebidBid; } catch (error) { - utils.logError(`${BIDDER_CODE}: Error while building bid`, error); + logError(`${BIDDER_CODE}: Error while building bid`, error); return null; } @@ -423,7 +425,7 @@ function getVideoSpecificParams(bidRequest, bid) { } function buildTargetingMap(bids) { - const impIds = bids.map(({ impid }) => impid).filter(utils.uniques); + const impIds = bids.map(({ impid }) => impid).filter(uniques); const values = impIds.reduce((result, id) => { result[id] = { lineItemIds: [], @@ -459,12 +461,12 @@ function buildTargetingMap(bids) { function hasRequiredParams(bidRequest) { const value = - utils.deepAccess(bidRequest, 'params.placementId') != null || - utils.deepAccess(bidRequest, 'params.orgId') != null || + deepAccess(bidRequest, 'params.placementId') != null || + deepAccess(bidRequest, 'params.orgId') != null || getBidderConfig('orgId') != null; if (!value) { - utils.logError(`${BIDDER_CODE}: missing orgId and placementId parameter`); + logError(`${BIDDER_CODE}: missing orgId and placementId parameter`); } return value; @@ -472,7 +474,7 @@ function hasRequiredParams(bidRequest) { function isValidBannerRequest(bidRequest) { const value = validateSizes( - utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes', []) + deepAccess(bidRequest, 'mediaTypes.banner.sizes', []) ); return value; @@ -480,28 +482,28 @@ function isValidBannerRequest(bidRequest) { function isValidVideoRequest(bidRequest) { const value = - utils.isArray(utils.deepAccess(bidRequest, 'mediaTypes.video.mimes')) && + isArray(deepAccess(bidRequest, 'mediaTypes.video.mimes')) && validateVideoSizes(bidRequest); return value; } function validateSize(size) { - return utils.isArray(size) && size.length === 2 && size.every(utils.isNumber); + return isArray(size) && size.length === 2 && size.every(isNumber); } function validateSizes(sizes) { - return utils.isArray(sizes) && sizes.length > 0 && sizes.every(validateSize); + return isArray(sizes) && sizes.length > 0 && sizes.every(validateSize); } function validateVideoSizes(bidRequest) { - const { w, h } = utils.deepAccess(bidRequest, 'mediaTypes.video', {}); + const { w, h } = deepAccess(bidRequest, 'mediaTypes.video', {}); return ( validateSizes( - utils.deepAccess(bidRequest, 'mediaTypes.video.playerSize') + deepAccess(bidRequest, 'mediaTypes.video.playerSize') ) || - (utils.isNumber(w) && utils.isNumber(h)) + (isNumber(w) && isNumber(h)) ); } @@ -518,7 +520,7 @@ function validateBid(bidderRequestBody) { const value = validators.every((validator) => validator(bid, bidRequest)); if (!value) { - utils.logWarn(`${BIDDER_CODE}: Invalid bid`, bid); + logWarn(`${BIDDER_CODE}: Invalid bid`, bid); } return value; @@ -526,13 +528,13 @@ function validateBid(bidderRequestBody) { } const commonBidValidators = [ - (bid) => utils.isPlainObject(bid), + (bid) => isPlainObject(bid), (bid) => isNonEmptyStr(bid.adid), (bid) => isNonEmptyStr(bid.adm), (bid) => isNonEmptyStr(bid.id), (bid) => isNonEmptyStr(bid.impid), - (bid) => isNonEmptyStr(utils.deepAccess(bid, 'ext.liid')), - (bid) => utils.isNumber(bid.price), + (bid) => isNonEmptyStr(deepAccess(bid, 'ext.liid')), + (bid) => isNumber(bid.price), ]; const bannerBidValidators = [ @@ -546,12 +548,12 @@ function validateBannerDimension(dimension) { return bannerHasSingleSize(bidRequest); } - return utils.isNumber(bid[dimension]); + return isNumber(bid[dimension]); }; } function bannerHasSingleSize(bidRequest) { - return utils.deepAccess(bidRequest, 'banner.format', []).length === 1; + return deepAccess(bidRequest, 'banner.format', []).length === 1; } /** @@ -562,9 +564,9 @@ export const storage = getStorageManager(); function getUserSyncs(syncOptions, responses, gdprConsent, uspConsent) { return responses - .map((response) => utils.deepAccess(response, 'body.ext.sync')) - .filter(utils.isArray) - .reduce(utils.flatten, []) + .map((response) => deepAccess(response, 'body.ext.sync')) + .filter(isArray) + .reduce(flatten, []) .filter(validateSync(syncOptions)) .map(applyConsents(gdprConsent, uspConsent)); } @@ -644,11 +646,11 @@ function onBidWon(bid) { const wurl = buildWinUrl(bid); if (wurl !== null) { - utils.triggerPixel(wurl); + triggerPixel(wurl); } - if (utils.isStr(bid.nurl)) { - utils.triggerPixel(bid.nurl); + if (isStr(bid.nurl)) { + triggerPixel(bid.nurl); } } @@ -662,7 +664,7 @@ function buildWinUrl(bid) { return url.toString(); } catch (_) { - utils.logError( + logError( `${BIDDER_CODE}: Could not build win tracking URL with %s`, getBidderConfig('winTrackingUrl') ); @@ -686,7 +688,7 @@ function getMediaType(adm) { const markup = safeJSONparse(adm.replace(/\\/g, '')); - if (markup && utils.isPlainObject(markup.native)) { + if (markup && isPlainObject(markup.native)) { return NATIVE; } @@ -702,7 +704,7 @@ function safeJSONparse(...args) { } function isNonEmptyStr(value) { - return utils.isStr(value) && !utils.isEmptyStr(value); + return isStr(value) && !isEmptyStr(value); } function findBidRequest(bidderRequest, bid) { @@ -782,7 +784,7 @@ const getUrlBuilder = function (url) { export const common = { generateUUID: function () { - return utils.generateUUID(); + return generateUUID(); }, getConfig: function (property) { return config.getConfig(property); diff --git a/modules/adfBidAdapter.js b/modules/adfBidAdapter.js index 2153f12316f..f7727a168b8 100644 --- a/modules/adfBidAdapter.js +++ b/modules/adfBidAdapter.js @@ -7,7 +7,7 @@ import { import { NATIVE, BANNER, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { mergeDeep, _map, deepAccess, parseSizesInput, deepSetValue } from '../src/utils.js'; import { config } from '../src/config.js'; import { Renderer } from '../src/Renderer.js'; @@ -68,12 +68,12 @@ export const spec = { if (typeof getConfig('app') === 'object') { app = getConfig('app') || {}; if (commonFpd.app) { - utils.mergeDeep(app, commonFpd.app); + mergeDeep(app, commonFpd.app); } } else { site = getConfig('site') || {}; if (commonFpd.site) { - utils.mergeDeep(site, commonFpd.site); + mergeDeep(site, commonFpd.site); } if (!site.page) { @@ -112,7 +112,7 @@ export const spec = { bidfloorcur }; - const assets = utils._map(bid.nativeParams, (bidParams, key) => { + const assets = _map(bid.nativeParams, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, @@ -158,10 +158,10 @@ export const spec = { return imp; } - const bannerParams = utils.deepAccess(bid, 'mediaTypes.banner'); + const bannerParams = deepAccess(bid, 'mediaTypes.banner'); if (bannerParams && bannerParams.sizes) { - const sizes = utils.parseSizesInput(bannerParams.sizes); + const sizes = parseSizesInput(bannerParams.sizes); const format = sizes.map(size => { const [ width, height ] = size.split('x'); const w = parseInt(width, 10); @@ -177,7 +177,7 @@ export const spec = { return imp; } - const videoParams = utils.deepAccess(bid, 'mediaTypes.video'); + const videoParams = deepAccess(bid, 'mediaTypes.video'); if (videoParams) { imp.video = videoParams; bid.mediaType = VIDEO; @@ -202,21 +202,21 @@ export const spec = { request.is_debug = !!test; request.test = 1; } - if (utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies') !== undefined) { - utils.deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(request, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); + if (deepAccess(bidderRequest, 'gdprConsent.gdprApplies') !== undefined) { + deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(request, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); } if (bidderRequest.uspConsent) { - utils.deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (eids) { - utils.deepSetValue(request, 'user.ext.eids', eids); + deepSetValue(request, 'user.ext.eids', eids); } if (schain) { - utils.deepSetValue(request, 'source.ext.schain', schain); + deepSetValue(request, 'source.ext.schain', schain); } return { @@ -266,7 +266,7 @@ export const spec = { result[ bid.mediaType === VIDEO ? 'vastXml' : 'ad' ] = bidResponse.adm; } - if (!bid.renderer && bid.mediaType === VIDEO && utils.deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { + if (!bid.renderer && bid.mediaType === VIDEO && deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { result.renderer = Renderer.install({id: bid.bidId, url: OUTSTREAM_RENDERER_URL, adUnitCode: bid.adUnitCode}); result.renderer.setRender(renderer); } @@ -300,7 +300,7 @@ function parseNative(bid) { function setOnAny(collection, key) { for (let i = 0, result; i < collection.length; i++) { - result = utils.deepAccess(collection[i], key); + result = deepAccess(collection[i], key); if (result) { return result; } diff --git a/modules/adgenerationBidAdapter.js b/modules/adgenerationBidAdapter.js index f43fd284bad..2696915ea0a 100644 --- a/modules/adgenerationBidAdapter.js +++ b/modules/adgenerationBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { tryAppendQueryString, getBidIdParameter } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, NATIVE} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -33,23 +33,23 @@ export const spec = { const URL = 'https://d.socdm.com/adsv/v1'; const url = validReq.params.debug ? DEBUG_URL : URL; let data = ``; - data = utils.tryAppendQueryString(data, 'posall', 'SSPLOC'); - const id = utils.getBidIdParameter('id', validReq.params); - data = utils.tryAppendQueryString(data, 'id', id); - data = utils.tryAppendQueryString(data, 'sdktype', '0'); - data = utils.tryAppendQueryString(data, 'hb', 'true'); - data = utils.tryAppendQueryString(data, 't', 'json3'); - data = utils.tryAppendQueryString(data, 'transactionid', validReq.transactionId); - data = utils.tryAppendQueryString(data, 'sizes', getSizes(validReq)); - data = utils.tryAppendQueryString(data, 'currency', getCurrencyType()); - data = utils.tryAppendQueryString(data, 'pbver', '$prebid.version$'); - data = utils.tryAppendQueryString(data, 'sdkname', 'prebidjs'); - data = utils.tryAppendQueryString(data, 'adapterver', ADGENE_PREBID_VERSION); + data = tryAppendQueryString(data, 'posall', 'SSPLOC'); + const id = getBidIdParameter('id', validReq.params); + data = tryAppendQueryString(data, 'id', id); + data = tryAppendQueryString(data, 'sdktype', '0'); + data = tryAppendQueryString(data, 'hb', 'true'); + data = tryAppendQueryString(data, 't', 'json3'); + data = tryAppendQueryString(data, 'transactionid', validReq.transactionId); + data = tryAppendQueryString(data, 'sizes', getSizes(validReq)); + data = tryAppendQueryString(data, 'currency', getCurrencyType()); + data = tryAppendQueryString(data, 'pbver', '$prebid.version$'); + data = tryAppendQueryString(data, 'sdkname', 'prebidjs'); + data = tryAppendQueryString(data, 'adapterver', ADGENE_PREBID_VERSION); // native以外にvideo等の対応が入った場合は要修正 if (!validReq.mediaTypes || !validReq.mediaTypes.native) { - data = utils.tryAppendQueryString(data, 'imark', '1'); + data = tryAppendQueryString(data, 'imark', '1'); } - data = utils.tryAppendQueryString(data, 'tp', bidderRequest.refererInfo.referer); + data = tryAppendQueryString(data, 'tp', bidderRequest.refererInfo.referer); // remove the trailing "&" if (data.lastIndexOf('&') === data.length - 1) { data = data.substring(0, data.length - 1); diff --git a/modules/adkernelAdnAnalyticsAdapter.js b/modules/adkernelAdnAnalyticsAdapter.js index 23501f7dd63..2b4e67736f3 100644 --- a/modules/adkernelAdnAnalyticsAdapter.js +++ b/modules/adkernelAdnAnalyticsAdapter.js @@ -1,7 +1,7 @@ import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; +import { logError, parseUrl, _each } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; import {config} from '../src/config.js'; @@ -90,7 +90,7 @@ analyticsAdapter.originEnableAnalytics = analyticsAdapter.enableAnalytics; analyticsAdapter.enableAnalytics = (config) => { if (!config.options.pubId) { - utils.logError('PubId is not defined. Analytics won\'t work'); + logError('PubId is not defined. Analytics won\'t work'); return; } analyticsAdapter.context = { @@ -215,7 +215,7 @@ export function getUmtSource(pageUrl, referrer) { if (se) { return asUtm(se, ORGANIC, ORGANIC); } - let parsedUrl = utils.parseUrl(pageUrl); + let parsedUrl = parseUrl(pageUrl); let [refHost, refPath] = getReferrer(referrer); if (refHost && refHost !== parsedUrl.hostname) { return asUtm(refHost, REFERRAL, REFERRAL, '', refPath); @@ -242,17 +242,17 @@ export function getUmtSource(pageUrl, referrer) { } function getReferrer(referrer) { - let ref = utils.parseUrl(referrer); + let ref = parseUrl(referrer); return [ref.hostname, ref.pathname]; } function getUTM(pageUrl) { - let urlParameters = utils.parseUrl(pageUrl).search; + let urlParameters = parseUrl(pageUrl).search; if (!urlParameters['utm_campaign'] || !urlParameters['utm_source']) { return; } let utmArgs = []; - utils._each(UTM_TAGS, (utmTagName) => { + _each(UTM_TAGS, (utmTagName) => { let utmValue = urlParameters[utmTagName] || ''; utmArgs.push(utmValue); }); diff --git a/modules/adkernelAdnBidAdapter.js b/modules/adkernelAdnBidAdapter.js index dc56ed6abbb..39f7b9fd2b2 100644 --- a/modules/adkernelAdnBidAdapter.js +++ b/modules/adkernelAdnBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, parseSizesInput, isArray, deepSetValue, parseUrl, isStr, isNumber, logInfo } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -19,12 +19,12 @@ function buildImp(bidRequest) { tagid: bidRequest.adUnitCode }; let mediaType; - let bannerReq = utils.deepAccess(bidRequest, `mediaTypes.banner`); - let videoReq = utils.deepAccess(bidRequest, `mediaTypes.video`); + let bannerReq = deepAccess(bidRequest, `mediaTypes.banner`); + let videoReq = deepAccess(bidRequest, `mediaTypes.video`); if (bannerReq) { let sizes = canonicalizeSizesArray(bannerReq.sizes); imp.banner = { - format: utils.parseSizesInput(sizes) + format: parseSizesInput(sizes) }; mediaType = BANNER; } else if (videoReq) { @@ -51,7 +51,7 @@ function buildImp(bidRequest) { * @return Array[Array[Number]] */ function canonicalizeSizesArray(sizes) { - if (sizes.length === 2 && !utils.isArray(sizes[0])) { + if (sizes.length === 2 && !isArray(sizes[0])) { return [sizes]; } return sizes; @@ -67,23 +67,23 @@ function buildRequestParams(tags, bidderRequest) { }; if (gdprConsent) { if (gdprConsent.gdprApplies !== undefined) { - utils.deepSetValue(req, 'user.gdpr', ~~gdprConsent.gdprApplies); + deepSetValue(req, 'user.gdpr', ~~gdprConsent.gdprApplies); } if (gdprConsent.consentString !== undefined) { - utils.deepSetValue(req, 'user.consent', gdprConsent.consentString); + deepSetValue(req, 'user.consent', gdprConsent.consentString); } } if (uspConsent) { - utils.deepSetValue(req, 'user.us_privacy', uspConsent); + deepSetValue(req, 'user.us_privacy', uspConsent); } if (config.getConfig('coppa')) { - utils.deepSetValue(req, 'user.coppa', 1); + deepSetValue(req, 'user.coppa', 1); } return req; } function buildSite(refInfo) { - let loc = utils.parseUrl(refInfo.referer); + let loc = parseUrl(refInfo.referer); let result = { page: `${loc.protocol}://${loc.hostname}${loc.pathname}`, secure: ~~(loc.protocol === 'https') @@ -126,23 +126,23 @@ function buildBid(tag) { } function fillBidMeta(bid, tag) { - if (utils.isStr(tag.agencyName)) { - utils.deepSetValue(bid, 'meta.agencyName', tag.agencyName); + if (isStr(tag.agencyName)) { + deepSetValue(bid, 'meta.agencyName', tag.agencyName); } - if (utils.isNumber(tag.advertiserId)) { - utils.deepSetValue(bid, 'meta.advertiserId', tag.advertiserId); + if (isNumber(tag.advertiserId)) { + deepSetValue(bid, 'meta.advertiserId', tag.advertiserId); } - if (utils.isStr(tag.advertiserName)) { - utils.deepSetValue(bid, 'meta.advertiserName', tag.advertiserName); + if (isStr(tag.advertiserName)) { + deepSetValue(bid, 'meta.advertiserName', tag.advertiserName); } - if (utils.isArray(tag.advertiserDomains)) { - utils.deepSetValue(bid, 'meta.advertiserDomains', tag.advertiserDomains); + if (isArray(tag.advertiserDomains)) { + deepSetValue(bid, 'meta.advertiserDomains', tag.advertiserDomains); } - if (utils.isStr(tag.primaryCatId)) { - utils.deepSetValue(bid, 'meta.primaryCatId', tag.primaryCatId); + if (isStr(tag.primaryCatId)) { + deepSetValue(bid, 'meta.primaryCatId', tag.primaryCatId); } - if (utils.isArray(tag.secondaryCatIds)) { - utils.deepSetValue(bid, 'meta.secondaryCatIds', tag.secondaryCatIds); + if (isArray(tag.secondaryCatIds)) { + deepSetValue(bid, 'meta.secondaryCatIds', tag.secondaryCatIds); } } @@ -204,7 +204,7 @@ export const spec = { return []; } if (response.debug) { - utils.logInfo(`ADKERNEL DEBUG:\n${response.debug}`); + logInfo(`ADKERNEL DEBUG:\n${response.debug}`); } return response.tags.map(buildBid); }, From 29f49e339b3cf502ecd46c6b966b8d5007fc348e Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 11:37:45 -0700 Subject: [PATCH 20/84] Multiple Bid/Analytics/ID Adapters: import utils functions as needed and not the whole module (#7477) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/adWMGBidAdapter.js | 8 +- modules/adriverBidAdapter.js | 26 +++--- modules/adtargetBidAdapter.js | 48 +++++------ modules/adtelligentBidAdapter.js | 58 ++++++------- modules/adtrueBidAdapter.js | 70 ++++++++-------- modules/aduptechBidAdapter.js | 20 ++--- modules/advangelistsBidAdapter.js | 28 +++---- modules/adxcgAnalyticsAdapter.js | 10 +-- modules/adxcgBidAdapter.js | 112 +++++++++++++------------- modules/adxpremiumAnalyticsAdapter.js | 34 ++++---- modules/adyoulikeBidAdapter.js | 22 ++--- modules/ajaBidAdapter.js | 24 +++--- modules/akamaiDAPIdSystem.js | 18 ++--- modules/aniviewBidAdapter.js | 4 +- modules/aolBidAdapter.js | 26 +++--- 15 files changed, 254 insertions(+), 254 deletions(-) diff --git a/modules/adWMGBidAdapter.js b/modules/adWMGBidAdapter.js index a3d78a69d91..7bf6c703a55 100644 --- a/modules/adWMGBidAdapter.js +++ b/modules/adWMGBidAdapter.js @@ -1,6 +1,6 @@ 'use strict'; -import * as utils from '../src/utils.js'; +import { tryAppendQueryString } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -128,11 +128,11 @@ export const spec = { }, getUserSyncs: (syncOptions, serverResponses, gdprConsent, uspConsent) => { if (gdprConsent && SYNC_ENDPOINT.indexOf('gdpr') === -1) { - SYNC_ENDPOINT = utils.tryAppendQueryString(SYNC_ENDPOINT, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); + SYNC_ENDPOINT = tryAppendQueryString(SYNC_ENDPOINT, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); } if (gdprConsent && typeof gdprConsent.consentString === 'string' && SYNC_ENDPOINT.indexOf('gdpr_consent') === -1) { - SYNC_ENDPOINT = utils.tryAppendQueryString(SYNC_ENDPOINT, 'gdpr_consent', gdprConsent.consentString); + SYNC_ENDPOINT = tryAppendQueryString(SYNC_ENDPOINT, 'gdpr_consent', gdprConsent.consentString); } if (SYNC_ENDPOINT.slice(-1) === '&') { @@ -140,7 +140,7 @@ export const spec = { } /* if (uspConsent) { - SYNC_ENDPOINT = utils.tryAppendQueryString(SYNC_ENDPOINT, 'us_privacy', uspConsent); + SYNC_ENDPOINT = tryAppendQueryString(SYNC_ENDPOINT, 'us_privacy', uspConsent); } */ let syncs = []; if (syncOptions.iframeEnabled) { diff --git a/modules/adriverBidAdapter.js b/modules/adriverBidAdapter.js index d5a777f6111..67e039e4692 100644 --- a/modules/adriverBidAdapter.js +++ b/modules/adriverBidAdapter.js @@ -1,5 +1,5 @@ // ADRIVER BID ADAPTER for Prebid 1.13 -import * as utils from '../src/utils.js'; +import { logInfo, getWindowLocation, getBidIdParameter, _each } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'adriver'; @@ -21,12 +21,12 @@ export const spec = { }, buildRequests: function (validBidRequests, bidderRequest) { - utils.logInfo('validBidRequests', validBidRequests); + logInfo('validBidRequests', validBidRequests); - let win = utils.getWindowLocation(); + let win = getWindowLocation(); let customID = Math.round(Math.random() * 999999999) + '-' + Math.round(new Date() / 1000) + '-1-46-'; - let siteId = utils.getBidIdParameter('siteid', validBidRequests[0].params) + ''; - let currency = utils.getBidIdParameter('currency', validBidRequests[0].params); + let siteId = getBidIdParameter('siteid', validBidRequests[0].params) + ''; + let currency = getBidIdParameter('currency', validBidRequests[0].params); currency = 'RUB'; let timeout = null; @@ -58,8 +58,8 @@ export const spec = { 'imp': [] }; - utils._each(validBidRequests, (bid) => { - utils._each(bid.sizes, (sizes) => { + _each(validBidRequests, (bid) => { + _each(bid.sizes, (sizes) => { let width; let height; let par; @@ -67,7 +67,7 @@ export const spec = { let floorAndCurrency = _getFloor(bid, currency, sizes); let bidFloor = floorAndCurrency.floor; - let dealId = utils.getBidIdParameter('dealid', bid.params); + let dealId = getBidIdParameter('dealid', bid.params); if (typeof sizes[0] === 'number' && typeof sizes[1] === 'number') { width = sizes[0]; height = sizes[1]; @@ -93,7 +93,7 @@ export const spec = { }] }; } - utils.logInfo('par', par); + logInfo('par', par); payload.imp.push(par); }); }); @@ -108,11 +108,11 @@ export const spec = { }, interpretResponse: function (serverResponse, bidRequest) { - utils.logInfo('serverResponse.body.seatbid', serverResponse.body.seatbid); + logInfo('serverResponse.body.seatbid', serverResponse.body.seatbid); const bidResponses = []; let nurl = 0; - utils._each(serverResponse.body.seatbid, (seatbid) => { - utils.logInfo('_each', seatbid); + _each(serverResponse.body.seatbid, (seatbid) => { + logInfo('_each', seatbid); var bid = seatbid.bid[0]; if (bid.nurl !== undefined) { nurl = bid.nurl.split('://'); @@ -135,7 +135,7 @@ export const spec = { }, ad: '' }; - utils.logInfo('bidResponse', bidResponse); + logInfo('bidResponse', bidResponse); bidResponses.push(bidResponse); } }); diff --git a/modules/adtargetBidAdapter.js b/modules/adtargetBidAdapter.js index 1779ba94371..0ad0177815a 100644 --- a/modules/adtargetBidAdapter.js +++ b/modules/adtargetBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isArray, chunk, _map, flatten, logError, parseSizesInput } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; @@ -13,7 +13,7 @@ export const spec = { code: BIDDER_CODE, supportedMediaTypes: [VIDEO, BANNER], isBidRequestValid: function (bid) { - return !!utils.deepAccess(bid, 'params.aid'); + return !!deepAccess(bid, 'params.aid'); }, getUserSyncs: function (syncOptions, serverResponses) { const syncs = []; @@ -42,9 +42,9 @@ export const spec = { } if (syncOptions.pixelEnabled || syncOptions.iframeEnabled) { - utils.isArray(serverResponses) && serverResponses.forEach((response) => { + isArray(serverResponses) && serverResponses.forEach((response) => { if (response.body) { - if (utils.isArray(response.body)) { + if (isArray(response.body)) { response.body.forEach(b => { addSyncs(b); }) @@ -59,10 +59,10 @@ export const spec = { buildRequests: function (bidRequests, adapterRequest) { const adapterSettings = config.getConfig(adapterRequest.bidderCode) - const chunkSize = utils.deepAccess(adapterSettings, 'chunkSize', 10); + const chunkSize = deepAccess(adapterSettings, 'chunkSize', 10); const { tag, bids } = bidToTag(bidRequests, adapterRequest); - const bidChunks = utils.chunk(bids, chunkSize); - return utils._map(bidChunks, (bids) => { + const bidChunks = chunk(bids, chunkSize); + return _map(bidChunks, (bids) => { return { data: Object.assign({}, tag, { BidRequests: bids }), adapterRequest, @@ -75,12 +75,12 @@ export const spec = { serverResponse = serverResponse.body; let bids = []; - if (!utils.isArray(serverResponse)) { + if (!isArray(serverResponse)) { return parseResponse(serverResponse, adapterRequest); } serverResponse.forEach(serverBidResponse => { - bids = utils.flatten(bids, parseResponse(serverBidResponse, adapterRequest)); + bids = flatten(bids, parseResponse(serverBidResponse, adapterRequest)); }); return bids; @@ -88,14 +88,14 @@ export const spec = { }; function parseResponse(serverResponse, adapterRequest) { - const isInvalidValidResp = !serverResponse || !utils.isArray(serverResponse.bids); + const isInvalidValidResp = !serverResponse || !isArray(serverResponse.bids); const bids = []; if (isInvalidValidResp) { const extMessage = serverResponse && serverResponse.ext && serverResponse.ext.message ? `: ${serverResponse.ext.message}` : ''; const errorMessage = `in response for ${adapterRequest.bidderCode} adapter ${extMessage}`; - utils.logError(errorMessage); + logError(errorMessage); return bids; } @@ -117,23 +117,23 @@ function parseResponse(serverResponse, adapterRequest) { function bidToTag(bidRequests, adapterRequest) { const tag = { - Domain: utils.deepAccess(adapterRequest, 'refererInfo.referer') + Domain: deepAccess(adapterRequest, 'refererInfo.referer') }; if (config.getConfig('coppa') === true) { tag.Coppa = 1; } - if (utils.deepAccess(adapterRequest, 'gdprConsent.gdprApplies')) { + if (deepAccess(adapterRequest, 'gdprConsent.gdprApplies')) { tag.GDPR = 1; - tag.GDPRConsent = utils.deepAccess(adapterRequest, 'gdprConsent.consentString'); + tag.GDPRConsent = deepAccess(adapterRequest, 'gdprConsent.consentString'); } - if (utils.deepAccess(adapterRequest, 'uspConsent')) { - tag.USP = utils.deepAccess(adapterRequest, 'uspConsent'); + if (deepAccess(adapterRequest, 'uspConsent')) { + tag.USP = deepAccess(adapterRequest, 'uspConsent'); } - if (utils.deepAccess(bidRequests[0], 'schain')) { - tag.Schain = utils.deepAccess(bidRequests[0], 'schain'); + if (deepAccess(bidRequests[0], 'schain')) { + tag.Schain = deepAccess(bidRequests[0], 'schain'); } - if (utils.deepAccess(bidRequests[0], 'userId')) { - tag.UserIds = utils.deepAccess(bidRequests[0], 'userId'); + if (deepAccess(bidRequests[0], 'userId')) { + tag.UserIds = deepAccess(bidRequests[0], 'userId'); } const bids = [] @@ -147,19 +147,19 @@ function bidToTag(bidRequests, adapterRequest) { } function prepareBidRequests(bidReq) { - const mediaType = utils.deepAccess(bidReq, 'mediaTypes.video') ? VIDEO : DISPLAY; - const sizes = mediaType === VIDEO ? utils.deepAccess(bidReq, 'mediaTypes.video.playerSize') : utils.deepAccess(bidReq, 'mediaTypes.banner.sizes'); + const mediaType = deepAccess(bidReq, 'mediaTypes.video') ? VIDEO : DISPLAY; + const sizes = mediaType === VIDEO ? deepAccess(bidReq, 'mediaTypes.video.playerSize') : deepAccess(bidReq, 'mediaTypes.banner.sizes'); const bidReqParams = { 'CallbackId': bidReq.bidId, 'Aid': bidReq.params.aid, 'AdType': mediaType, - 'Sizes': utils.parseSizesInput(sizes).join(',') + 'Sizes': parseSizesInput(sizes).join(',') }; return bidReqParams; } function getMediaType(bidderRequest) { - return utils.deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; + return deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; } function createBid(bidResponse, bidRequest) { diff --git a/modules/adtelligentBidAdapter.js b/modules/adtelligentBidAdapter.js index e1c6dc1ca35..8523e01c0ea 100644 --- a/modules/adtelligentBidAdapter.js +++ b/modules/adtelligentBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isArray, chunk, _map, flatten, convertTypes, parseSizesInput } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { ADPOD, BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; @@ -44,7 +44,7 @@ export const spec = { ], supportedMediaTypes: [VIDEO, BANNER], isBidRequestValid: function (bid) { - return !!utils.deepAccess(bid, 'params.aid'); + return !!deepAccess(bid, 'params.aid'); }, getUserSyncs: function (syncOptions, serverResponses) { const syncs = []; @@ -73,9 +73,9 @@ export const spec = { } if (syncOptions.pixelEnabled || syncOptions.iframeEnabled) { - utils.isArray(serverResponses) && serverResponses.forEach((response) => { + isArray(serverResponses) && serverResponses.forEach((response) => { if (response.body) { - if (utils.isArray(response.body)) { + if (isArray(response.body)) { response.body.forEach(b => { addSyncs(b); }) @@ -94,10 +94,10 @@ export const spec = { */ buildRequests: function (bidRequests, adapterRequest) { const adapterSettings = config.getConfig(adapterRequest.bidderCode) - const chunkSize = utils.deepAccess(adapterSettings, 'chunkSize', 10); + const chunkSize = deepAccess(adapterSettings, 'chunkSize', 10); const { tag, bids } = bidToTag(bidRequests, adapterRequest); - const bidChunks = utils.chunk(bids, chunkSize); - return utils._map(bidChunks, (bids) => { + const bidChunks = chunk(bids, chunkSize); + return _map(bidChunks, (bids) => { return { data: Object.assign({}, tag, { BidRequests: bids }), adapterRequest, @@ -117,26 +117,26 @@ export const spec = { serverResponse = serverResponse.body; let bids = []; - if (!utils.isArray(serverResponse)) { + if (!isArray(serverResponse)) { return parseRTBResponse(serverResponse, adapterRequest); } serverResponse.forEach(serverBidResponse => { - bids = utils.flatten(bids, parseRTBResponse(serverBidResponse, adapterRequest)); + bids = flatten(bids, parseRTBResponse(serverBidResponse, adapterRequest)); }); return bids; }, transformBidParams(params) { - return utils.convertTypes({ + return convertTypes({ 'aid': 'number', }, params); } }; function parseRTBResponse(serverResponse, adapterRequest) { - const isEmptyResponse = !serverResponse || !utils.isArray(serverResponse.bids); + const isEmptyResponse = !serverResponse || !isArray(serverResponse.bids); const bids = []; if (isEmptyResponse) { @@ -161,26 +161,26 @@ function parseRTBResponse(serverResponse, adapterRequest) { function bidToTag(bidRequests, adapterRequest) { // start publisher env const tag = { - Domain: utils.deepAccess(adapterRequest, 'refererInfo.referer') + Domain: deepAccess(adapterRequest, 'refererInfo.referer') }; if (config.getConfig('coppa') === true) { tag.Coppa = 1; } - if (utils.deepAccess(adapterRequest, 'gdprConsent.gdprApplies')) { + if (deepAccess(adapterRequest, 'gdprConsent.gdprApplies')) { tag.GDPR = 1; - tag.GDPRConsent = utils.deepAccess(adapterRequest, 'gdprConsent.consentString'); + tag.GDPRConsent = deepAccess(adapterRequest, 'gdprConsent.consentString'); } - if (utils.deepAccess(adapterRequest, 'uspConsent')) { - tag.USP = utils.deepAccess(adapterRequest, 'uspConsent'); + if (deepAccess(adapterRequest, 'uspConsent')) { + tag.USP = deepAccess(adapterRequest, 'uspConsent'); } - if (utils.deepAccess(bidRequests[0], 'schain')) { - tag.Schain = utils.deepAccess(bidRequests[0], 'schain'); + if (deepAccess(bidRequests[0], 'schain')) { + tag.Schain = deepAccess(bidRequests[0], 'schain'); } - if (utils.deepAccess(bidRequests[0], 'userId')) { - tag.UserIds = utils.deepAccess(bidRequests[0], 'userId'); + if (deepAccess(bidRequests[0], 'userId')) { + tag.UserIds = deepAccess(bidRequests[0], 'userId'); } - if (utils.deepAccess(bidRequests[0], 'userIdAsEids')) { - tag.UserEids = utils.deepAccess(bidRequests[0], 'userIdAsEids'); + if (deepAccess(bidRequests[0], 'userIdAsEids')) { + tag.UserEids = deepAccess(bidRequests[0], 'userIdAsEids'); } if (window.adtDmp && window.adtDmp.ready) { tag.DMPId = window.adtDmp.getUID(); @@ -203,13 +203,13 @@ function bidToTag(bidRequests, adapterRequest) { * @returns {object} */ function prepareBidRequests(bidReq) { - const mediaType = utils.deepAccess(bidReq, 'mediaTypes.video') ? VIDEO : DISPLAY; - const sizes = mediaType === VIDEO ? utils.deepAccess(bidReq, 'mediaTypes.video.playerSize') : utils.deepAccess(bidReq, 'mediaTypes.banner.sizes'); + const mediaType = deepAccess(bidReq, 'mediaTypes.video') ? VIDEO : DISPLAY; + const sizes = mediaType === VIDEO ? deepAccess(bidReq, 'mediaTypes.video.playerSize') : deepAccess(bidReq, 'mediaTypes.banner.sizes'); const bidReqParams = { 'CallbackId': bidReq.bidId, 'Aid': bidReq.params.aid, 'AdType': mediaType, - 'Sizes': utils.parseSizesInput(sizes).join(',') + 'Sizes': parseSizesInput(sizes).join(',') }; bidReqParams.PlacementId = bidReq.adUnitCode; @@ -220,9 +220,9 @@ function prepareBidRequests(bidReq) { bidReqParams.PlacementId = bidReq.params.vpb_placement_id; } if (mediaType === VIDEO) { - const context = utils.deepAccess(bidReq, 'mediaTypes.video.context'); + const context = deepAccess(bidReq, 'mediaTypes.video.context'); if (context === ADPOD) { - bidReqParams.Adpod = utils.deepAccess(bidReq, 'mediaTypes.video'); + bidReqParams.Adpod = deepAccess(bidReq, 'mediaTypes.video'); } } return bidReqParams; @@ -234,7 +234,7 @@ function prepareBidRequests(bidReq) { * @returns {object} */ function getMediaType(bidderRequest) { - return utils.deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; + return deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; } /** @@ -245,7 +245,7 @@ function getMediaType(bidderRequest) { */ function createBid(bidResponse, bidRequest) { const mediaType = getMediaType(bidRequest) - const context = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const context = deepAccess(bidRequest, 'mediaTypes.video.context'); const bid = { requestId: bidResponse.requestId, creativeId: bidResponse.cmpId, diff --git a/modules/adtrueBidAdapter.js b/modules/adtrueBidAdapter.js index 96f1ceb12f0..df848fba823 100644 --- a/modules/adtrueBidAdapter.js +++ b/modules/adtrueBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, isArray, inIframe, isNumber, isStr, deepClone, deepSetValue, logError, deepAccess, isBoolean } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -190,22 +190,22 @@ function _checkParamDataType(key, value, datatype) { var functionToExecute; switch (datatype) { case DATA_TYPES.BOOLEAN: - functionToExecute = utils.isBoolean; + functionToExecute = isBoolean; break; case DATA_TYPES.NUMBER: - functionToExecute = utils.isNumber; + functionToExecute = isNumber; break; case DATA_TYPES.STRING: - functionToExecute = utils.isStr; + functionToExecute = isStr; break; case DATA_TYPES.ARRAY: - functionToExecute = utils.isArray; + functionToExecute = isArray; break; } if (functionToExecute(value)) { return value; } - utils.logWarn(LOG_WARN_PREFIX + errMsg); + logWarn(LOG_WARN_PREFIX + errMsg); return UNDEFINED; } @@ -216,7 +216,7 @@ function _parseNativeResponse(bid, newBid) { try { adm = JSON.parse(bid.adm.replace(/\\/g, '')); } catch (ex) { - // utils.logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + newBid.adm); + // logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + newBid.adm); return; } if (adm && adm.native && adm.native.assets && adm.native.assets.length > 0) { @@ -274,13 +274,13 @@ function _createBannerRequest(bid) { var sizes = bid.mediaTypes.banner.sizes; var format = []; var bannerObj; - if (sizes !== UNDEFINED && utils.isArray(sizes)) { + if (sizes !== UNDEFINED && isArray(sizes)) { bannerObj = {}; if (!bid.params.width && !bid.params.height) { if (sizes.length === 0) { // i.e. since bid.params does not have width or height, and length of sizes is 0, need to ignore this banner imp bannerObj = UNDEFINED; - utils.logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); return bannerObj; } else { bannerObj.w = parseInt(sizes[0][0], 10); @@ -303,9 +303,9 @@ function _createBannerRequest(bid) { } } bannerObj.pos = 0; - bannerObj.topframe = utils.inIframe() ? 0 : 1; + bannerObj.topframe = inIframe() ? 0 : 1; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); bannerObj = UNDEFINED; } return bannerObj; @@ -323,10 +323,10 @@ function _createVideoRequest(bid) { } } // read playersize and assign to h and w. - if (utils.isArray(bid.mediaTypes.video.playerSize[0])) { + if (isArray(bid.mediaTypes.video.playerSize[0])) { videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0][0], 10); videoObj.h = parseInt(bid.mediaTypes.video.playerSize[0][1], 10); - } else if (utils.isNumber(bid.mediaTypes.video.playerSize[0])) { + } else if (isNumber(bid.mediaTypes.video.playerSize[0])) { videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0], 10); videoObj.h = parseInt(bid.mediaTypes.video.playerSize[1], 10); } @@ -337,7 +337,7 @@ function _createVideoRequest(bid) { } } else { videoObj = UNDEFINED; - utils.logWarn(LOG_WARN_PREFIX + 'Error: Video config params missing for adunit: ' + bid.params.adUnit + ' with mediaType set as video. Ignoring video impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: Video config params missing for adunit: ' + bid.params.adUnit + ' with mediaType set as video. Ignoring video impression in the adunit.'); } return videoObj; } @@ -355,7 +355,7 @@ function _checkMediaType(adm, newBid) { newBid.mediaType = NATIVE; } } catch (e) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + adm); + logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + adm); } } } @@ -401,9 +401,9 @@ function _createImpressionObject(bid, conf) { pos: 0, w: bid.params.width, h: bid.params.height, - topframe: utils.inIframe() ? 0 : 1 + topframe: inIframe() ? 0 : 1 }; - if (utils.isArray(sizes) && sizes.length > 1) { + if (isArray(sizes) && sizes.length > 1) { sizes = sizes.splice(1, sizes.length - 1); sizes.forEach(size => { format.push({ @@ -428,19 +428,19 @@ export const spec = { isBidRequestValid: function (bid) { if (bid && bid.params) { if (!bid.params.zoneId) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: missing zoneId'); + logWarn(LOG_WARN_PREFIX + 'Error: missing zoneId'); return false; } if (!bid.params.publisherId) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: missing publisherId'); + logWarn(LOG_WARN_PREFIX + 'Error: missing publisherId'); return false; } - if (!utils.isStr(bid.params.publisherId)) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: publisherId is mandatory and cannot be numeric'); + if (!isStr(bid.params.publisherId)) { + logWarn(LOG_WARN_PREFIX + 'Error: publisherId is mandatory and cannot be numeric'); return false; } - if (!utils.isStr(bid.params.zoneId)) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: zoneId is mandatory and cannot be numeric'); + if (!isStr(bid.params.zoneId)) { + logWarn(LOG_WARN_PREFIX + 'Error: zoneId is mandatory and cannot be numeric'); return false; } return true; @@ -458,7 +458,7 @@ export const spec = { let bidCurrency = ''; let bid; validBidRequests.forEach(originalBid => { - bid = utils.deepClone(originalBid); + bid = deepClone(originalBid); _parseAdSlot(bid); conf.zoneId = conf.zoneId || bid.params.zoneId; @@ -468,7 +468,7 @@ export const spec = { if (bidCurrency === '') { bidCurrency = bid.params.currency || UNDEFINED; } else if (bid.params.hasOwnProperty('currency') && bidCurrency !== bid.params.currency) { - utils.logWarn(LOG_WARN_PREFIX + 'Currency specifier ignored. Only one currency permitted.'); + logWarn(LOG_WARN_PREFIX + 'Currency specifier ignored. Only one currency permitted.'); } bid.params.currency = bidCurrency; @@ -502,28 +502,28 @@ export const spec = { if (typeof config.getConfig('device') === 'object') { payload.device = Object.assign(payload.device, config.getConfig('device')); } - utils.deepSetValue(payload, 'source.tid', conf.transactionId); + deepSetValue(payload, 'source.tid', conf.transactionId); // test bids if (window.location.href.indexOf('adtrueTest=true') !== -1) { payload.test = 1; } // adding schain object if (validBidRequests[0].schain) { - utils.deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); + deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); } // Attaching GDPR Consent Params if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); } // CCPA if (bidderRequest && bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } // coppa compliance if (config.getConfig('coppa') === true) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } return { @@ -539,12 +539,12 @@ export const spec = { let parsedRequest = JSON.parse(bidderRequest.data); let parsedReferrer = parsedRequest.site && parsedRequest.site.ref ? parsedRequest.site.ref : ''; try { - if (serverResponses.body && serverResponses.body.seatbid && utils.isArray(serverResponses.body.seatbid)) { + if (serverResponses.body && serverResponses.body.seatbid && isArray(serverResponses.body.seatbid)) { // Supporting multiple bid responses for same adSize respCur = serverResponses.body.cur || respCur; serverResponses.body.seatbid.forEach(seatbidder => { seatbidder.bid && - utils.isArray(seatbidder.bid) && + isArray(seatbidder.bid) && seatbidder.bid.forEach(bid => { let newBid = { requestId: bid.impid, @@ -598,7 +598,7 @@ export const spec = { }); } } catch (error) { - utils.logError(error); + logError(error); } return bidResponses; }, @@ -607,7 +607,7 @@ export const spec = { return []; } return responses.reduce((accum, rsp) => { - let cookieSyncs = utils.deepAccess(rsp, 'body.ext.cookie_sync'); + let cookieSyncs = deepAccess(rsp, 'body.ext.cookie_sync'); if (cookieSyncs) { let cookieSyncObjects = cookieSyncs.map(cookieSync => { return { diff --git a/modules/aduptechBidAdapter.js b/modules/aduptechBidAdapter.js index b70f7cf3ce6..1186e0410ab 100644 --- a/modules/aduptechBidAdapter.js +++ b/modules/aduptechBidAdapter.js @@ -1,7 +1,7 @@ +import { deepAccess, getWindowTop, getWindowSelf, getAdUnitSizes } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js' -import * as utils from '../src/utils.js'; export const BIDDER_CODE = 'aduptech'; export const ENDPOINT_URL_PUBLISHER_PLACEHOLDER = '{PUBLISHER}'; @@ -37,7 +37,7 @@ export const internal = { * @returns {string} */ extractPageUrl: (bidderRequest) => { - if (bidderRequest && utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl')) { + if (bidderRequest && deepAccess(bidderRequest, 'refererInfo.canonicalUrl')) { return bidderRequest.refererInfo.canonicalUrl; } @@ -46,9 +46,9 @@ export const internal = { } try { - return utils.getWindowTop().location.href; + return getWindowTop().location.href; } catch (e) { - return utils.getWindowSelf().location.href; + return getWindowSelf().location.href; } }, @@ -59,14 +59,14 @@ export const internal = { * @returns {string} */ extractReferrer: (bidderRequest) => { - if (bidderRequest && utils.deepAccess(bidderRequest, 'refererInfo.referer')) { + if (bidderRequest && deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } try { - return utils.getWindowTop().document.referrer; + return getWindowTop().document.referrer; } catch (e) { - return utils.getWindowSelf().document.referrer; + return getWindowSelf().document.referrer; } }, @@ -77,7 +77,7 @@ export const internal = { * @returns {null|Object.} */ extractBannerConfig: (bidRequest) => { - const sizes = utils.getAdUnitSizes(bidRequest); + const sizes = getAdUnitSizes(bidRequest); if (Array.isArray(sizes) && sizes.length > 0) { return { sizes: sizes }; } @@ -92,7 +92,7 @@ export const internal = { * @returns {null|Object.} */ extractNativeConfig: (bidRequest) => { - if (bidRequest && utils.deepAccess(bidRequest, 'mediaTypes.native')) { + if (bidRequest && deepAccess(bidRequest, 'mediaTypes.native')) { return bidRequest.mediaTypes.native; } @@ -267,7 +267,7 @@ export const spec = { const bidResponses = []; // stop here on invalid or empty data - if (!response || !utils.deepAccess(response, 'body.bids') || response.body.bids.length === 0) { + if (!response || !deepAccess(response, 'body.bids') || response.body.bids.length === 0) { return bidResponses; } diff --git a/modules/advangelistsBidAdapter.js b/modules/advangelistsBidAdapter.js index edf58fefd64..854c65b1f22 100755 --- a/modules/advangelistsBidAdapter.js +++ b/modules/advangelistsBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isEmpty, deepAccess, isFn, parseSizesInput, generateUUID, parseUrl } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { VIDEO, BANNER } from '../src/mediaTypes.js'; @@ -56,7 +56,7 @@ export const spec = { interpretResponse(serverResponse, {bidRequest}) { let response = serverResponse.body; - if (response !== null && utils.isEmpty(response) == false) { + if (response !== null && isEmpty(response) == false) { if (isVideoBid(bidRequest)) { let bidResponse = { requestId: response.id, @@ -103,20 +103,20 @@ export const spec = { }; function isBannerBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); + return deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); } function isVideoBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.video'); + return deepAccess(bid, 'mediaTypes.video'); } function getBannerBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: 'USD', mediaType: 'banner', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: 'USD', mediaType: 'banner', size: '*' }) : {}; return floorInfo.floor || getBannerBidParam(bid, 'bidfloor'); } function getVideoBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: 'USD', mediaType: 'video', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: 'USD', mediaType: 'video', size: '*' }) : {}; return floorInfo.floor || getVideoBidParam(bid, 'bidfloor'); } @@ -129,11 +129,11 @@ function isBannerBidValid(bid) { } function getVideoBidParam(bid, key) { - return utils.deepAccess(bid, 'params.video.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.video.' + key) || deepAccess(bid, 'params.' + key); } function getBannerBidParam(bid, key) { - return utils.deepAccess(bid, 'params.banner.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.banner.' + key) || deepAccess(bid, 'params.' + key); } function isMobile() { @@ -184,7 +184,7 @@ function getFirstSize(sizes) { } function parseSizes(sizes) { - return utils.parseSizesInput(sizes).map(size => { + return parseSizesInput(sizes).map(size => { let [ width, height ] = size.split('x'); return { w: parseInt(width, 10) || undefined, @@ -194,11 +194,11 @@ function parseSizes(sizes) { } function getVideoSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } function getBannerSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } function getTopWindowReferrer() { @@ -290,7 +290,7 @@ function createVideoRequestData(bid, bidderRequest) { 'bidfloorcur': 'USD', 'secure': secure, 'video': Object.assign({ - 'id': utils.generateUUID(), + 'id': generateUUID(), 'pos': 0, 'w': firstSize.w, 'h': firstSize.h, @@ -311,7 +311,7 @@ function createVideoRequestData(bid, bidderRequest) { function getTopWindowLocation(bidderRequest) { let url = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer; - return utils.parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); + return parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); } function createBannerRequestData(bid, bidderRequest) { @@ -378,7 +378,7 @@ function createBannerRequestData(bid, bidderRequest) { 'bidfloorcur': 'USD', 'secure': secure, 'banner': { - 'id': utils.generateUUID(), + 'id': generateUUID(), 'pos': 0, 'w': size['w'], 'h': size['h'] diff --git a/modules/adxcgAnalyticsAdapter.js b/modules/adxcgAnalyticsAdapter.js index 9f514c545a1..5cd04ce13cd 100644 --- a/modules/adxcgAnalyticsAdapter.js +++ b/modules/adxcgAnalyticsAdapter.js @@ -1,8 +1,8 @@ +import { parseSizesInput, uniques, buildUrl, logError } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; /** * Analytics adapter from adxcg.com @@ -32,7 +32,7 @@ var adxcgAnalyticsAdapter = Object.assign(adapter( case CONSTANTS.EVENTS.BID_ADJUSTMENT: break; case CONSTANTS.EVENTS.BID_TIMEOUT: - adxcgAnalyticsAdapter.context.events.bidTimeout = args.map(item => item.bidder).filter(utils.uniques); + adxcgAnalyticsAdapter.context.events.bidTimeout = args.map(item => item.bidder).filter(uniques); break; case CONSTANTS.EVENTS.BIDDER_DONE: break; @@ -67,7 +67,7 @@ function mapBidRequested (bidRequests) { adUnitCode: bid.adUnitCode, bidId: bid.bidId, start: bid.startTime, - sizes: utils.parseSizesInput(bid.sizes).toString(), + sizes: parseSizesInput(bid.sizes).toString(), params: bid.params }; }), @@ -112,7 +112,7 @@ function mapBidWon (bidResponse) { } function send (data) { - let adxcgAnalyticsRequestUrl = utils.buildUrl({ + let adxcgAnalyticsRequestUrl = buildUrl({ protocol: 'https', hostname: adxcgAnalyticsAdapter.context.host, pathname: '/pbrx/v2', @@ -143,7 +143,7 @@ adxcgAnalyticsAdapter.context = {}; adxcgAnalyticsAdapter.originEnableAnalytics = adxcgAnalyticsAdapter.enableAnalytics; adxcgAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.publisherId) { - utils.logError('PublisherId option is not defined. Analytics won\'t work'); + logError('PublisherId option is not defined. Analytics won\'t work'); return; } diff --git a/modules/adxcgBidAdapter.js b/modules/adxcgBidAdapter.js index e10eeaa3302..a02812a1608 100644 --- a/modules/adxcgBidAdapter.js +++ b/modules/adxcgBidAdapter.js @@ -1,5 +1,5 @@ +import { logWarn, isStr, deepAccess, inIframe, checkCookieSupport, timestamp, getBidIdParameter, parseSizesInput, buildUrl, logMessage, isArray, deepSetValue, isPlainObject, triggerPixel, replaceAuctionPrice, isFn } from '../src/utils.js'; import {config} from '../src/config.js' -import * as utils from '../src/utils.js' import {registerBidder} from '../src/adapters/bidderFactory.js' import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js' import includes from 'core-js-pure/features/array/includes.js' @@ -36,44 +36,44 @@ export const spec = { */ isBidRequestValid: function (bid) { if (!bid || !bid.params) { - utils.logWarn(BIDDER_CODE + ': Missing bid parameters'); + logWarn(BIDDER_CODE + ': Missing bid parameters'); return false } - if (!utils.isStr(bid.params.adzoneid)) { - utils.logWarn(BIDDER_CODE + ': adzoneid must be specified as a string'); + if (!isStr(bid.params.adzoneid)) { + logWarn(BIDDER_CODE + ': adzoneid must be specified as a string'); return false } if (isBannerRequest(bid)) { - const banneroAdUnit = utils.deepAccess(bid, 'mediaTypes.banner'); + const banneroAdUnit = deepAccess(bid, 'mediaTypes.banner'); if (!banneroAdUnit.sizes) { - utils.logWarn(BIDDER_CODE + ': banner sizes must be specified'); + logWarn(BIDDER_CODE + ': banner sizes must be specified'); return false; } } if (isVideoRequest(bid)) { // prebid 4.0 use standardized Video parameters - const videoAdUnit = utils.deepAccess(bid, 'mediaTypes.video'); + const videoAdUnit = deepAccess(bid, 'mediaTypes.video'); if (!Array.isArray(videoAdUnit.playerSize)) { - utils.logWarn(BIDDER_CODE + ': video playerSize must be an array of integers'); + logWarn(BIDDER_CODE + ': video playerSize must be an array of integers'); return false; } if (!videoAdUnit.context) { - utils.logWarn(BIDDER_CODE + ': video context must be specified'); + logWarn(BIDDER_CODE + ': video context must be specified'); return false; } if (!Array.isArray(videoAdUnit.mimes) || videoAdUnit.mimes.length === 0) { - utils.logWarn(BIDDER_CODE + ': video mimes must be an array of strings'); + logWarn(BIDDER_CODE + ': video mimes must be an array of strings'); return false; } if (!Array.isArray(videoAdUnit.protocols) || videoAdUnit.protocols.length === 0) { - utils.logWarn(BIDDER_CODE + ': video protocols must be an array of integers'); + logWarn(BIDDER_CODE + ': video protocols must be an array of integers'); return false; } } @@ -97,8 +97,8 @@ export const spec = { bt = Math.min(window.PREBID_TIMEOUT, bt); } - let referrer = utils.deepAccess(bidderRequest, 'refererInfo.referer'); - let page = utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); + let referrer = deepAccess(bidderRequest, 'refererInfo.referer'); + let page = deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || deepAccess(window, 'location.href'); // add common parameters let beaconParams = { @@ -110,10 +110,10 @@ export const spec = { uh: window.screen.height, dpr: ratio, bt: bt, - isinframe: utils.inIframe(), - cookies: utils.checkCookieSupport() ? '1' : '0', + isinframe: inIframe(), + cookies: checkCookieSupport() ? '1' : '0', tz: dt.getTimezoneOffset(), - dt: utils.timestamp(), + dt: timestamp(), iob: iobavailable ? '1' : '0', pbjs: '$prebid.version$', rndid: Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000, @@ -126,19 +126,19 @@ export const spec = { beaconParams.gdpr_consent = bidderRequest.gdprConsent.consentString; } - if (utils.isStr(utils.deepAccess(validBidRequests, '0.userId.pubcid'))) { + if (isStr(deepAccess(validBidRequests, '0.userId.pubcid'))) { beaconParams.pubcid = validBidRequests[0].userId.pubcid; } - if (utils.isStr(utils.deepAccess(validBidRequests, '0.userId.tdid'))) { + if (isStr(deepAccess(validBidRequests, '0.userId.tdid'))) { beaconParams.tdid = validBidRequests[0].userId.tdid; } - if (utils.isStr(utils.deepAccess(validBidRequests, '0.userId.id5id.uid'))) { + if (isStr(deepAccess(validBidRequests, '0.userId.id5id.uid'))) { beaconParams.id5id = validBidRequests[0].userId.id5id.uid; } - if (utils.isStr(utils.deepAccess(validBidRequests, '0.userId.idl_env'))) { + if (isStr(deepAccess(validBidRequests, '0.userId.idl_env'))) { beaconParams.idl_env = validBidRequests[0].userId.idl_env; } @@ -156,14 +156,14 @@ export const spec = { let bidfloors = []; validBidRequests.forEach((bid, index) => { - adZoneIds.push(utils.getBidIdParameter('adzoneid', bid.params)); + adZoneIds.push(getBidIdParameter('adzoneid', bid.params)); prebidBidIds.push(bid.bidId); let bidfloor = getFloor(bid); bidfloors.push(bidfloor); // copy all custom parameters impression level parameters not supported above - let customBidParams = utils.getBidIdParameter('custom', bid.params) || {} + let customBidParams = getBidIdParameter('custom', bid.params) || {} if (customBidParams) { Object.keys(customBidParams) .filter(param => includes(USER_PARAMS_BID, param)) @@ -171,7 +171,7 @@ export const spec = { } if (isBannerRequest(bid)) { - sizes.push(utils.parseSizesInput(bid.mediaTypes.banner.sizes).join('|')); + sizes.push(parseSizesInput(bid.mediaTypes.banner.sizes).join('|')); } if (isNativeRequest(bid)) { @@ -185,10 +185,10 @@ export const spec = { .forEach(param => beaconParams['video.' + param + '.' + index] = encodeURIComponent(bid.params.video[param])) } // copy video standarized params - beaconParams['video.context' + '.' + index] = utils.deepAccess(bid, 'mediaTypes.video.context'); - sizes.push(utils.parseSizesInput(bid.mediaTypes.video.playerSize).join('|')); - beaconParams['video.mimes' + '.' + index] = utils.deepAccess(bid, 'mediaTypes.video.mimes').join(','); - beaconParams['video.protocols' + '.' + index] = utils.deepAccess(bid, 'mediaTypes.video.protocols').join(','); + beaconParams['video.context' + '.' + index] = deepAccess(bid, 'mediaTypes.video.context'); + sizes.push(parseSizesInput(bid.mediaTypes.video.playerSize).join('|')); + beaconParams['video.mimes' + '.' + index] = deepAccess(bid, 'mediaTypes.video.mimes').join(','); + beaconParams['video.protocols' + '.' + index] = deepAccess(bid, 'mediaTypes.video.protocols').join(','); } }) @@ -197,14 +197,14 @@ export const spec = { beaconParams.prebidBidIds = prebidBidIds.join(','); beaconParams.bidfloors = bidfloors.join(','); - let adxcgRequestUrl = utils.buildUrl({ + let adxcgRequestUrl = buildUrl({ protocol: 'https', hostname: 'hbps.adxcg.net', pathname: '/get/adi', search: beaconParams }); - utils.logMessage(`calling adi adxcg`); + logMessage(`calling adi adxcg`); return { contentType: 'text/plain', method: 'GET', @@ -220,11 +220,11 @@ export const spec = { */ interpretResponse: function (serverResponse) { - utils.logMessage(`interpretResponse adxcg`); + logMessage(`interpretResponse adxcg`); let bidsAll = []; - if (!serverResponse || !serverResponse.body || !utils.isArray(serverResponse.body.seatbid) || !serverResponse.body.seatbid.length) { - utils.logWarn(BIDDER_CODE + ': empty bid response'); + if (!serverResponse || !serverResponse.body || !isArray(serverResponse.body.seatbid) || !serverResponse.body.seatbid.length) { + logWarn(BIDDER_CODE + ': empty bid response'); return bidsAll; } @@ -256,28 +256,28 @@ export const spec = { bid.mediaType = 'native'; bid.native = parseNative(JSON.parse(serverResponseOneItem.adm)); } else { - utils.logWarn(BIDDER_CODE + ': unknown or undefined crType'); + logWarn(BIDDER_CODE + ': unknown or undefined crType'); } // prebid 4.0 meta taxonomy - if (utils.isArray(serverResponseOneItem.adomain)) { - utils.deepSetValue(bid, 'meta.advertiserDomains', serverResponseOneItem.adomain); + if (isArray(serverResponseOneItem.adomain)) { + deepSetValue(bid, 'meta.advertiserDomains', serverResponseOneItem.adomain); } - if (utils.isArray(serverResponseOneItem.cat)) { - utils.deepSetValue(bid, 'meta.secondaryCatIds', serverResponseOneItem.cat); + if (isArray(serverResponseOneItem.cat)) { + deepSetValue(bid, 'meta.secondaryCatIds', serverResponseOneItem.cat); } - if (utils.isPlainObject(serverResponseOneItem.ext)) { - if (utils.isStr(serverResponseOneItem.ext.advertiser_id)) { - utils.deepSetValue(bid, 'meta.mediaType', serverResponseOneItem.ext.mediaType); + if (isPlainObject(serverResponseOneItem.ext)) { + if (isStr(serverResponseOneItem.ext.advertiser_id)) { + deepSetValue(bid, 'meta.mediaType', serverResponseOneItem.ext.mediaType); } - if (utils.isStr(serverResponseOneItem.ext.advertiser_id)) { - utils.deepSetValue(bid, 'meta.advertiserId', serverResponseOneItem.ext.advertiser_id); + if (isStr(serverResponseOneItem.ext.advertiser_id)) { + deepSetValue(bid, 'meta.advertiserId', serverResponseOneItem.ext.advertiser_id); } - if (utils.isStr(serverResponseOneItem.ext.advertiser_name)) { - utils.deepSetValue(bid, 'meta.advertiserName', serverResponseOneItem.ext.advertiser_name); + if (isStr(serverResponseOneItem.ext.advertiser_name)) { + deepSetValue(bid, 'meta.advertiserName', serverResponseOneItem.ext.advertiser_name); } - if (utils.isStr(serverResponseOneItem.ext.agency_name)) { - utils.deepSetValue(bid, 'meta.agencyName', serverResponseOneItem.ext.agency_name); + if (isStr(serverResponseOneItem.ext.agency_name)) { + deepSetValue(bid, 'meta.agencyName', serverResponseOneItem.ext.agency_name); } } bidsAll.push(bid) @@ -288,7 +288,7 @@ export const spec = { onBidWon: (bid) => { if (bid.burl) { - utils.triggerPixel(utils.replaceAuctionPrice(bid.burl, bid.originalCpm)); + triggerPixel(replaceAuctionPrice(bid.burl, bid.originalCpm)); } }, @@ -304,14 +304,14 @@ export const spec = { cn: timeoutData.timeout, aud: timeoutData.auctionId, }; - let adxcgRequestUrl = utils.buildUrl({ + let adxcgRequestUrl = buildUrl({ protocol: 'https', hostname: 'hbps.adxcg.net', pathname: '/event/timeout.gif', search: beaconParams }); - utils.logWarn(BIDDER_CODE + ': onTimeout called'); - utils.triggerPixel(adxcgRequestUrl); + logWarn(BIDDER_CODE + ': onTimeout called'); + triggerPixel(adxcgRequestUrl); }, getUserSyncs: function (syncOptions, serverResponses, gdprConsent) { @@ -336,20 +336,20 @@ export const spec = { } function isVideoRequest(bid) { - return bid.mediaType === 'video' || !!utils.deepAccess(bid, 'mediaTypes.video'); + return bid.mediaType === 'video' || !!deepAccess(bid, 'mediaTypes.video'); } function isBannerRequest(bid) { - return bid.mediaType === 'banner' || !!utils.deepAccess(bid, 'mediaTypes.banner'); + return bid.mediaType === 'banner' || !!deepAccess(bid, 'mediaTypes.banner'); } function isNativeRequest(bid) { - return bid.mediaType === 'native' || !!utils.deepAccess(bid, 'mediaTypes.native'); + return bid.mediaType === 'native' || !!deepAccess(bid, 'mediaTypes.native'); } function getFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.floor', DEFAULT_MIN_FLOOR); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.floor', DEFAULT_MIN_FLOOR); } try { @@ -361,7 +361,7 @@ function getFloor(bid) { }); return floor.floor; } catch (e) { - utils.logWarn(BIDDER_CODE + ': call to getFloor failed:' + e.message); + logWarn(BIDDER_CODE + ': call to getFloor failed:' + e.message); return DEFAULT_MIN_FLOOR; } } diff --git a/modules/adxpremiumAnalyticsAdapter.js b/modules/adxpremiumAnalyticsAdapter.js index f11e3b8d4e5..3e30de14052 100644 --- a/modules/adxpremiumAnalyticsAdapter.js +++ b/modules/adxpremiumAnalyticsAdapter.js @@ -1,8 +1,8 @@ +import { logError, logInfo, deepClone } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; import includes from 'core-js-pure/features/array/includes.js'; const analyticsType = 'endpoint'; @@ -95,7 +95,7 @@ function auctionInit(args) { completeObject.auction_id = args.auctionId; completeObject.publisher_id = adxpremiumAnalyticsAdapter.initOptions.pubId; - try { completeObject.referer = encodeURI(args.bidderRequests[0].refererInfo.referer.split('?')[0]); } catch (e) { utils.logError('AdxPremium Analytics - ' + e.message); } + try { completeObject.referer = encodeURI(args.bidderRequests[0].refererInfo.referer.split('?')[0]); } catch (e) { logError('AdxPremium Analytics - ' + e.message); } if (args.adUnitCodes && args.adUnitCodes.length > 0) { elementIds = args.adUnitCodes; } @@ -140,20 +140,20 @@ function bidWon(args) { if (requestDelivered) { if (completeObject.events[eventIndex]) { // do the upgrade - utils.logInfo('AdxPremium Analytics - Upgrading request'); + logInfo('AdxPremium Analytics - Upgrading request'); completeObject.events[eventIndex].is_winning = true; completeObject.events[eventIndex].is_upgrade = true; - upgradedObject = utils.deepClone(completeObject); + upgradedObject = deepClone(completeObject); upgradedObject.events = [completeObject.events[eventIndex]]; sendEvent(upgradedObject); // send upgrade } else { - utils.logInfo('AdxPremium Analytics - CANNOT FIND INDEX FOR REQUEST ' + args.requestId); + logInfo('AdxPremium Analytics - CANNOT FIND INDEX FOR REQUEST ' + args.requestId); } } else { completeObject.events[eventIndex].is_winning = true; } } else { - utils.logInfo('AdxPremium Analytics - Response not found, creating new one.'); + logInfo('AdxPremium Analytics - Response not found, creating new one.'); let tmpObject = { type: 'RESPONSE', bidder_code: args.bidderCode, @@ -167,14 +167,14 @@ function bidWon(args) { is_winning: true, is_lost: true }; - let lostObject = utils.deepClone(completeObject); + let lostObject = deepClone(completeObject); lostObject.events = [tmpObject]; sendEvent(lostObject); // send lost object } } function bidTimeout(args) { - let timeoutObject = utils.deepClone(completeObject); + let timeoutObject = deepClone(completeObject); timeoutObject.events = []; let usedRequestIds = []; @@ -191,12 +191,12 @@ function bidTimeout(args) { if (timeoutObject.events.length > 0) { sendEvent(timeoutObject); // send timeouted - utils.logInfo('AdxPremium Analytics - Sending timeouted requests'); + logInfo('AdxPremium Analytics - Sending timeouted requests'); } } function auctionEnd(args) { - utils.logInfo('AdxPremium Analytics - Auction Ended at ' + Date.now()); + logInfo('AdxPremium Analytics - Auction Ended at ' + Date.now()); if (timeoutBased) { setTimeout(function () { requestSent = true; sendEvent(completeObject); }, 3500); } else { sendEventFallback(); } } @@ -212,22 +212,22 @@ function deviceType() { } function clearSlot(elementId) { - if (includes(elementIds, elementId)) { elementIds.splice(elementIds.indexOf(elementId), 1); utils.logInfo('AdxPremium Analytics - Done with: ' + elementId); } + if (includes(elementIds, elementId)) { elementIds.splice(elementIds.indexOf(elementId), 1); logInfo('AdxPremium Analytics - Done with: ' + elementId); } if (elementIds.length == 0 && !requestSent && !timeoutBased) { requestSent = true; sendEvent(completeObject); - utils.logInfo('AdxPremium Analytics - Everything ready'); + logInfo('AdxPremium Analytics - Everything ready'); } } export function testSend() { sendEvent(completeObject); - utils.logInfo('AdxPremium Analytics - Sending without any conditions, used for testing'); + logInfo('AdxPremium Analytics - Sending without any conditions, used for testing'); } function sendEventFallback() { setTimeout(function () { - if (!requestSent) { requestSent = true; sendEvent(completeObject); utils.logInfo('AdxPremium Analytics - Sending event using fallback method.'); } + if (!requestSent) { requestSent = true; sendEvent(completeObject); logInfo('AdxPremium Analytics - Sending event using fallback method.'); } }, 2000); } @@ -241,11 +241,11 @@ function sendEvent(completeObject) { if (adxpremiumAnalyticsAdapter.initOptions.sid) { ajaxEndpoint = 'https://' + adxpremiumAnalyticsAdapter.initOptions.sid + '.adxpremium.services/graphql' } - ajax(ajaxEndpoint, function () { utils.logInfo('AdxPremium Analytics - Sending complete events at ' + Date.now()) }, dataToSend, { + ajax(ajaxEndpoint, function () { logInfo('AdxPremium Analytics - Sending complete events at ' + Date.now()) }, dataToSend, { contentType: 'application/json', method: 'POST' }); - } catch (err) { utils.logError('AdxPremium Analytics - Sending event error: ' + err); } + } catch (err) { logError('AdxPremium Analytics - Sending event error: ' + err); } } // save the base class function @@ -256,7 +256,7 @@ adxpremiumAnalyticsAdapter.enableAnalytics = function (config) { adxpremiumAnalyticsAdapter.initOptions = config.options; if (!config.options.pubId) { - utils.logError('AdxPremium Analytics - Publisher ID (pubId) option is not defined. Analytics won\'t work'); + logError('AdxPremium Analytics - Publisher ID (pubId) option is not defined. Analytics won\'t work'); return; } diff --git a/modules/adyoulikeBidAdapter.js b/modules/adyoulikeBidAdapter.js index 38731fdc91c..334309aec5c 100644 --- a/modules/adyoulikeBidAdapter.js +++ b/modules/adyoulikeBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, buildUrl, parseSizesInput } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import find from 'core-js-pure/features/array/find.js'; @@ -175,11 +175,11 @@ function getCanonicalUrl() { /* Get mediatype from bidRequest */ function getMediatype(bidRequest) { - if (utils.deepAccess(bidRequest, 'mediaTypes.video')) { + if (deepAccess(bidRequest, 'mediaTypes.video')) { return VIDEO; - } else if (utils.deepAccess(bidRequest, 'mediaTypes.banner')) { + } else if (deepAccess(bidRequest, 'mediaTypes.banner')) { return BANNER; - } else if (utils.deepAccess(bidRequest, 'mediaTypes.native')) { + } else if (deepAccess(bidRequest, 'mediaTypes.native')) { return NATIVE; } } @@ -210,7 +210,7 @@ function getPageRefreshed() { /* Create endpoint url */ function createEndpoint(bidRequests, bidderRequest) { let host = getHostname(bidRequests); - return utils.buildUrl({ + return buildUrl({ protocol: 'https', host: `${DEFAULT_DC}${host}.omnitagjs.com`, pathname: '/hb-api/prebid/v1', @@ -260,7 +260,7 @@ function getSizeArray(bid) { } } - return utils.parseSizesInput(inputSize); + return parseSizesInput(inputSize); } /* Get parsed size from request size */ @@ -342,7 +342,7 @@ function getVideoAd(response) { var adJson = {}; if (typeof response.Ad === 'string') { adJson = JSON.parse(response.Ad.match(/\/\*PREBID\*\/(.*)\/\*PREBID\*\//)[1]); - return utils.deepAccess(adJson, 'Content.MainVideo.Vast'); + return deepAccess(adJson, 'Content.MainVideo.Vast'); } } @@ -404,7 +404,7 @@ function getNativeAssets(response, nativeConfig) { imgSize[1] = response.Height || 250; } - const url = getImageUrl(adJson, utils.deepAccess(adJson, 'Content.Preview.Thumbnail.Image'), imgSize[0], imgSize[1]); + const url = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Thumbnail.Image'), imgSize[0], imgSize[1]); if (url) { native[key] = { url, @@ -422,7 +422,7 @@ function getNativeAssets(response, nativeConfig) { iconSize[1] = 50; } - const icurl = getImageUrl(adJson, utils.deepAccess(adJson, 'Content.Preview.Sponsor.Logo.Resource'), iconSize[0], iconSize[1]); + const icurl = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Sponsor.Logo.Resource'), iconSize[0], iconSize[1]); if (url) { native[key] = { @@ -433,10 +433,10 @@ function getNativeAssets(response, nativeConfig) { } break; case 'privacyIcon': - native[key] = getImageUrl(adJson, utils.deepAccess(adJson, 'Content.Preview.Credit.Logo.Resource'), 25, 25); + native[key] = getImageUrl(adJson, deepAccess(adJson, 'Content.Preview.Credit.Logo.Resource'), 25, 25); break; case 'privacyLink': - native[key] = utils.deepAccess(adJson, 'Content.Preview.Credit.Url'); + native[key] = deepAccess(adJson, 'Content.Preview.Credit.Url'); break; } }); diff --git a/modules/ajaBidAdapter.js b/modules/ajaBidAdapter.js index f7a9bfe5793..a9364a7a05f 100644 --- a/modules/ajaBidAdapter.js +++ b/modules/ajaBidAdapter.js @@ -1,5 +1,5 @@ +import { getBidIdParameter, tryAppendQueryString, createTrackPixelHtml, logError, logWarn } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { VIDEO, BANNER, NATIVE } from '../src/mediaTypes.js'; @@ -42,20 +42,20 @@ export const spec = { const bidRequest = validBidRequests[i]; let queryString = ''; - const asi = utils.getBidIdParameter('asi', bidRequest.params); - queryString = utils.tryAppendQueryString(queryString, 'asi', asi); - queryString = utils.tryAppendQueryString(queryString, 'skt', SDK_TYPE); - queryString = utils.tryAppendQueryString(queryString, 'tid', bidRequest.transactionId) - queryString = utils.tryAppendQueryString(queryString, 'prebid_id', bidRequest.bidId); - queryString = utils.tryAppendQueryString(queryString, 'prebid_ver', '$prebid.version$'); + const asi = getBidIdParameter('asi', bidRequest.params); + queryString = tryAppendQueryString(queryString, 'asi', asi); + queryString = tryAppendQueryString(queryString, 'skt', SDK_TYPE); + queryString = tryAppendQueryString(queryString, 'tid', bidRequest.transactionId) + queryString = tryAppendQueryString(queryString, 'prebid_id', bidRequest.bidId); + queryString = tryAppendQueryString(queryString, 'prebid_ver', '$prebid.version$'); if (pageUrl) { - queryString = utils.tryAppendQueryString(queryString, 'page_url', pageUrl); + queryString = tryAppendQueryString(queryString, 'page_url', pageUrl); } const eids = bidRequest.userIdAsEids; if (eids && eids.length) { - queryString = utils.tryAppendQueryString(queryString, 'eids', JSON.stringify({ + queryString = tryAppendQueryString(queryString, 'eids', JSON.stringify({ 'eids': eids, })) } @@ -114,11 +114,11 @@ export const spec = { }); try { bannerAd.imps.forEach(impTracker => { - const tracker = utils.createTrackPixelHtml(impTracker); + const tracker = createTrackPixelHtml(impTracker); bid.ad += tracker; }); } catch (error) { - utils.logError('Error appending tracking pixel', error); + logError('Error appending tracking pixel', error); } Array.prototype.push.apply(bid.meta.advertiserDomains, bannerAd.adomain) @@ -207,7 +207,7 @@ function newRenderer(bidderResponse) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on newRenderer', err); + logWarn('Prebid Error calling setRender on newRenderer', err); } return renderer; diff --git a/modules/akamaiDAPIdSystem.js b/modules/akamaiDAPIdSystem.js index a78d65b40a9..5e3a607d5fd 100644 --- a/modules/akamaiDAPIdSystem.js +++ b/modules/akamaiDAPIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logMessage, logError } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -29,7 +29,7 @@ export const akamaiDAPIdSubmodule = { * @returns {{dapId:string}} */ decode(value) { - utils.logMessage('akamaiDAPId [decode] value=', value); + logMessage('akamaiDAPId [decode] value=', value); return { dapId: value }; }, @@ -43,23 +43,23 @@ export const akamaiDAPIdSubmodule = { getId(config, consentData) { const configParams = (config && config.params); if (!configParams) { - utils.logError('User ID - akamaiDAPId submodule requires a valid configParams'); + logError('User ID - akamaiDAPId submodule requires a valid configParams'); return; } else if (typeof configParams.apiHostname !== 'string') { - utils.logError('User ID - akamaiDAPId submodule requires a valid configParams.apiHostname'); + logError('User ID - akamaiDAPId submodule requires a valid configParams.apiHostname'); return; } else if (typeof configParams.domain !== 'string') { - utils.logError('User ID - akamaiDAPId submodule requires a valid configParams.domain'); + logError('User ID - akamaiDAPId submodule requires a valid configParams.domain'); return; } else if (typeof configParams.type !== 'string') { - utils.logError('User ID - akamaiDAPId submodule requires a valid configParams.type'); + logError('User ID - akamaiDAPId submodule requires a valid configParams.type'); return; } const hasGdpr = (consentData && typeof consentData.gdprApplies === 'boolean' && consentData.gdprApplies) ? 1 : 0; const gdprConsentString = hasGdpr ? consentData.consentString : ''; const uspConsent = uspDataHandler.getConsentData(); if (hasGdpr && (!gdprConsentString || gdprConsentString === '')) { - utils.logError('User ID - akamaiDAPId submodule requires consent string to call API'); + logError('User ID - akamaiDAPId submodule requires consent string to call API'); return; } // XXX: retrieve first-party data here if needed @@ -99,14 +99,14 @@ export const akamaiDAPIdSubmodule = { storage.setDataInLocalStorage(STORAGE_KEY, token); }, error: error => { - utils.logError('akamaiDAPId [getId:ajax.error] failed to retrieve ' + tokenName, error); + logError('akamaiDAPId [getId:ajax.error] failed to retrieve ' + tokenName, error); } }; ajax(url, cb, JSON.stringify(postData), { contentType: 'application/json' }); let token = storage.getDataFromLocalStorage(STORAGE_KEY); - utils.logMessage('akamaiDAPId [getId] returning', token); + logMessage('akamaiDAPId [getId] returning', token); return { id: token }; } diff --git a/modules/aniviewBidAdapter.js b/modules/aniviewBidAdapter.js index 83a1ab20bb4..96bdf153e3f 100644 --- a/modules/aniviewBidAdapter.js +++ b/modules/aniviewBidAdapter.js @@ -1,7 +1,7 @@ import { VIDEO, BANNER } from '../src/mediaTypes.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; +import { logError } from '../src/utils.js'; const BIDDER_CODE = 'aniview'; const GVLID = 780; @@ -224,7 +224,7 @@ function interpretResponse(serverResponse, bidRequest) { }); bidResponse.vastUrl = window.URL.createObjectURL(blob); } catch (ex) { - utils.logError('Aniview Debug create vastXml error:\n\n' + ex); + logError('Aniview Debug create vastXml error:\n\n' + ex); } bidResponse.vastXml = xmlStr; if (bidRequest.bidRequest && bidRequest.bidRequest.mediaTypes && bidRequest.bidRequest.mediaTypes.video && bidRequest.bidRequest.mediaTypes.video.context === 'outstream') { diff --git a/modules/aolBidAdapter.js b/modules/aolBidAdapter.js index 4ab6f53ebdc..7203439059b 100644 --- a/modules/aolBidAdapter.js +++ b/modules/aolBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isInteger, logError, isEmpty, logWarn, getUniqueIdentifierStr, _each, deepSetValue } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -64,7 +64,7 @@ function template(strings, ...keys) { let dict = values[values.length - 1] || {}; let result = [strings[0]]; keys.forEach(function (key, i) { - let value = utils.isInteger(key) ? values[key] : dict[key]; + let value = isInteger(key) ? values[key] : dict[key]; result.push(value, strings[i + 1]); }); return result.join(''); @@ -147,7 +147,7 @@ export const spec = { }, interpretResponse({ body }, bidRequest) { if (!body) { - utils.logError('Empty bid response', bidRequest.bidderCode, body); + logError('Empty bid response', bidRequest.bidderCode, body); } else { let bid = this._parseBidResponse(body, bidRequest); @@ -157,7 +157,7 @@ export const spec = { } }, getUserSyncs(options, serverResponses) { - const bidResponse = !utils.isEmpty(serverResponses) && serverResponses[0].body; + const bidResponse = !isEmpty(serverResponses) && serverResponses[0].body; if (bidResponse && bidResponse.ext && bidResponse.ext.pixels) { return this.parsePixelItems(bidResponse.ext.pixels); @@ -215,7 +215,7 @@ export const spec = { let server; if (!MP_SERVER_MAP.hasOwnProperty(regionParam)) { - utils.logWarn(`Unknown region '${regionParam}' for AOL bidder.`); + logWarn(`Unknown region '${regionParam}' for AOL bidder.`); regionParam = 'us'; // Default region. } @@ -234,7 +234,7 @@ export const spec = { placement: parseInt(params.placement), pageid: params.pageId || 0, sizeid: params.sizeId || 0, - alias: params.alias || utils.getUniqueIdentifierStr(), + alias: params.alias || getUniqueIdentifierStr(), misc: new Date().getTime(), // cache busting dynamicParams: this.formatMarketplaceDynamicParams(params, consentData) })); @@ -273,7 +273,7 @@ export const spec = { Object.assign(queryParams, this.formatConsentData(consentData)); let paramsFormatted = ''; - utils._each(queryParams, (value, key) => { + _each(queryParams, (value, key) => { paramsFormatted += `${key}=${encodeURIComponent(value)};`; }); @@ -287,7 +287,7 @@ export const spec = { Object.assign(params, this.formatConsentData(consentData)); let paramsFormatted = ''; - utils._each(params, (value, key) => { + _each(params, (value, key) => { paramsFormatted += `&${key}=${encodeURIComponent(value)}`; }); @@ -300,14 +300,14 @@ export const spec = { }; if (this.isEUConsentRequired(consentData)) { - utils.deepSetValue(openRtbObject, 'regs.ext.gdpr', NUMERIC_VALUES.TRUE); + deepSetValue(openRtbObject, 'regs.ext.gdpr', NUMERIC_VALUES.TRUE); if (consentData.gdpr.consentString) { - utils.deepSetValue(openRtbObject, 'user.ext.consent', consentData.gdpr.consentString); + deepSetValue(openRtbObject, 'user.ext.consent', consentData.gdpr.consentString); } } if (consentData.uspConsent) { - utils.deepSetValue(openRtbObject, 'regs.ext.us_privacy', consentData.uspConsent); + deepSetValue(openRtbObject, 'regs.ext.us_privacy', consentData.uspConsent); } if (typeof bid.userId === 'object') { @@ -328,7 +328,7 @@ export const spec = { formatKeyValues(keyValues) { let keyValuesHash = {}; - utils._each(keyValues, (value, key) => { + _each(keyValues, (value, key) => { keyValuesHash[`kv${key}`] = value; }); @@ -394,7 +394,7 @@ export const spec = { cpm = bidData.price; if (cpm === null || isNaN(cpm)) { - utils.logError('Invalid price in bid response', AOL_BIDDERS_CODES.AOL, bidData); + logError('Invalid price in bid response', AOL_BIDDERS_CODES.AOL, bidData); return; } } From a75058777d9346cc8e4f902108602f3e91a21d88 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 12:32:17 -0700 Subject: [PATCH 21/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7490) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/krushmediaBidAdapter.js | 8 ++-- modules/kubientBidAdapter.js | 10 ++--- modules/limelightDigitalBidAdapter.js | 8 ++-- modules/liveIntentIdSystem.js | 9 ++--- modules/livewrappedAnalyticsAdapter.js | 26 ++++++------- modules/livewrappedBidAdapter.js | 14 +++---- modules/liveyieldAnalyticsAdapter.js | 26 ++++++------- modules/lockerdomeBidAdapter.js | 4 +- modules/loganBidAdapter.js | 8 ++-- modules/lotamePanoramaIdSystem.js | 26 ++++++------- modules/lunamediahbBidAdapter.js | 4 +- modules/madvertiseBidAdapter.js | 6 +-- modules/marsmediaBidAdapter.js | 52 +++++++++++++------------- modules/mathildeadsBidAdapter.js | 10 ++--- modules/mediaforceBidAdapter.js | 22 +++++------ 15 files changed, 116 insertions(+), 117 deletions(-) diff --git a/modules/krushmediaBidAdapter.js b/modules/krushmediaBidAdapter.js index db024230e2a..da68bddcb7b 100644 --- a/modules/krushmediaBidAdapter.js +++ b/modules/krushmediaBidAdapter.js @@ -1,6 +1,6 @@ +import { isFn, deepAccess, logMessage } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'krushmedia'; const AD_URL = 'https://ads4.krushmedia.com/?c=rtb&m=hb'; @@ -24,8 +24,8 @@ function isBidResponseValid(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -56,7 +56,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; const placements = []; diff --git a/modules/kubientBidAdapter.js b/modules/kubientBidAdapter.js index 6751a8a567c..07c614230a7 100644 --- a/modules/kubientBidAdapter.js +++ b/modules/kubientBidAdapter.js @@ -1,6 +1,6 @@ +import { isArray, deepAccess } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'kubient'; const END_POINT = 'https://kssp.kbntx.ch/kubprebidjs'; @@ -96,7 +96,7 @@ export const spec = { ad: bid.adm, meta: {} }; - if (bid.meta && bid.meta.adomain && utils.isArray(bid.meta.adomain)) { + if (bid.meta && bid.meta.adomain && isArray(bid.meta.adomain)) { bidResponse.meta.advertiserDomains = bid.meta.adomain; } if (bid.mediaType === VIDEO) { @@ -137,13 +137,13 @@ export const spec = { function kubientGetConsentGiven(gdprConsent) { let consentGiven = 0; if (typeof gdprConsent !== 'undefined') { - let apiVersion = utils.deepAccess(gdprConsent, `apiVersion`); + let apiVersion = deepAccess(gdprConsent, `apiVersion`); switch (apiVersion) { case 1: - consentGiven = utils.deepAccess(gdprConsent, `vendorData.vendorConsents.${VENDOR_ID}`) ? 1 : 0; + consentGiven = deepAccess(gdprConsent, `vendorData.vendorConsents.${VENDOR_ID}`) ? 1 : 0; break; case 2: - consentGiven = utils.deepAccess(gdprConsent, `vendorData.vendor.consents.${VENDOR_ID}`) ? 1 : 0; + consentGiven = deepAccess(gdprConsent, `vendorData.vendor.consents.${VENDOR_ID}`) ? 1 : 0; break; } } diff --git a/modules/limelightDigitalBidAdapter.js b/modules/limelightDigitalBidAdapter.js index 6203e22d253..5ad20924067 100644 --- a/modules/limelightDigitalBidAdapter.js +++ b/modules/limelightDigitalBidAdapter.js @@ -1,7 +1,7 @@ +import { logMessage, groupBy, uniques } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import {ajax} from '../src/ajax.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'limelightDigital'; @@ -51,10 +51,10 @@ export const spec = { winTop = window.top; winTop.location.toString(); } catch (e) { - utils.logMessage(e); + logMessage(e); winTop = window; } - const placements = utils.groupBy(validBidRequests.map(bidRequest => buildPlacement(bidRequest)), 'host') + const placements = groupBy(validBidRequests.map(bidRequest => buildPlacement(bidRequest)), 'host') return Object.keys(placements) .map(host => buildRequest(winTop, host, placements[host].map(placement => placement.adUnit))); }, @@ -125,7 +125,7 @@ function buildPlacement(bidRequest) { break; } } - sizes = (sizes || []).concat(bidRequest.sizes || []).filter(utils.uniques); + sizes = (sizes || []).concat(bidRequest.sizes || []).filter(uniques); return { host: bidRequest.params.host, adUnit: { diff --git a/modules/liveIntentIdSystem.js b/modules/liveIntentIdSystem.js index 5a955eefa92..91415daa497 100644 --- a/modules/liveIntentIdSystem.js +++ b/modules/liveIntentIdSystem.js @@ -4,8 +4,7 @@ * @module modules/liveIntentIdSystem * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; -import { triggerPixel } from '../src/utils.js'; +import { triggerPixel, logError } from '../src/utils.js'; import { ajaxBuilder } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { LiveConnect } from 'live-connect-js/esm/initializer.js'; @@ -93,8 +92,8 @@ function initializeLiveConnect(configParams) { liveConnectConfig.gdprConsent = gdprConsent.consentString; } - // The second param is the storage object, LS & Cookie manipulation uses PBJS utils. - // The third param is the ajax and pixel object, the ajax and pixel use PBJS utils. + // The second param is the storage object, LS & Cookie manipulation uses PBJS + // The third param is the ajax and pixel object, the ajax and pixel use PBJS liveConnect = liveIntentIdSubmodule.getInitializer()(liveConnectConfig, storage, calls); if (configParams.emailHash) { liveConnect.push({ hash: configParams.emailHash }) @@ -169,7 +168,7 @@ export const liveIntentIdSubmodule = { callback(response); }, error => { - utils.logError(`${MODULE_NAME}: ID fetch encountered an error: `, error); + logError(`${MODULE_NAME}: ID fetch encountered an error: `, error); callback(); } ) diff --git a/modules/livewrappedAnalyticsAdapter.js b/modules/livewrappedAnalyticsAdapter.js index 29b57e3dd97..03e5eea6974 100644 --- a/modules/livewrappedAnalyticsAdapter.js +++ b/modules/livewrappedAnalyticsAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { timestamp, logInfo, getWindowTop } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; @@ -21,16 +21,16 @@ const cache = { let livewrappedAnalyticsAdapter = Object.assign(adapter({EMPTYURL, ANALYTICSTYPE}), { track({eventType, args}) { - const time = utils.timestamp(); - utils.logInfo('LIVEWRAPPED_EVENT:', [eventType, args]); + const time = timestamp(); + logInfo('LIVEWRAPPED_EVENT:', [eventType, args]); switch (eventType) { case CONSTANTS.EVENTS.AUCTION_INIT: - utils.logInfo('LIVEWRAPPED_AUCTION_INIT:', args); + logInfo('LIVEWRAPPED_AUCTION_INIT:', args); cache.auctions[args.auctionId] = {bids: {}, bidAdUnits: {}}; break; case CONSTANTS.EVENTS.BID_REQUESTED: - utils.logInfo('LIVEWRAPPED_BID_REQUESTED:', args); + logInfo('LIVEWRAPPED_BID_REQUESTED:', args); cache.auctions[args.auctionId].timeStamp = args.start; args.bids.forEach(function(bidRequest) { @@ -62,12 +62,12 @@ let livewrappedAnalyticsAdapter = Object.assign(adapter({EMPTYURL, ANALYTICSTYPE lw: bidRequest.lw } - utils.logInfo(bidRequest); + logInfo(bidRequest); }) - utils.logInfo(livewrappedAnalyticsAdapter.requestEvents); + logInfo(livewrappedAnalyticsAdapter.requestEvents); break; case CONSTANTS.EVENTS.BID_RESPONSE: - utils.logInfo('LIVEWRAPPED_BID_RESPONSE:', args); + logInfo('LIVEWRAPPED_BID_RESPONSE:', args); let bidResponse = cache.auctions[args.auctionId].bids[args.requestId]; bidResponse.isBid = args.getStatusCode() === CONSTANTS.STATUS.GOOD; @@ -90,7 +90,7 @@ let livewrappedAnalyticsAdapter = Object.assign(adapter({EMPTYURL, ANALYTICSTYPE } break; case CONSTANTS.EVENTS.BIDDER_DONE: - utils.logInfo('LIVEWRAPPED_BIDDER_DONE:', args); + logInfo('LIVEWRAPPED_BIDDER_DONE:', args); args.bids.forEach(doneBid => { let bid = cache.auctions[doneBid.auctionId].bids[doneBid.bidId || doneBid.requestId]; if (!bid.ttr) { @@ -100,7 +100,7 @@ let livewrappedAnalyticsAdapter = Object.assign(adapter({EMPTYURL, ANALYTICSTYPE }); break; case CONSTANTS.EVENTS.BID_WON: - utils.logInfo('LIVEWRAPPED_BID_WON:', args); + logInfo('LIVEWRAPPED_BID_WON:', args); let wonBid = cache.auctions[args.auctionId].bids[args.requestId]; wonBid.won = true; if (wonBid.sendStatus != 0) { @@ -108,13 +108,13 @@ let livewrappedAnalyticsAdapter = Object.assign(adapter({EMPTYURL, ANALYTICSTYPE } break; case CONSTANTS.EVENTS.BID_TIMEOUT: - utils.logInfo('LIVEWRAPPED_BID_TIMEOUT:', args); + logInfo('LIVEWRAPPED_BID_TIMEOUT:', args); args.forEach(timeout => { cache.auctions[timeout.auctionId].bids[timeout.bidId].timeout = true; }); break; case CONSTANTS.EVENTS.AUCTION_END: - utils.logInfo('LIVEWRAPPED_AUCTION_END:', args); + logInfo('LIVEWRAPPED_AUCTION_END:', args); setTimeout(() => { livewrappedAnalyticsAdapter.sendEvents(); }, BID_WON_TIMEOUT); @@ -159,7 +159,7 @@ livewrappedAnalyticsAdapter.sendEvents = function() { function getAdblockerRecovered() { try { - return utils.getWindowTop().I12C && utils.getWindowTop().I12C.Morph === 1; + return getWindowTop().I12C && getWindowTop().I12C.Morph === 1; } catch (e) {} } diff --git a/modules/livewrappedBidAdapter.js b/modules/livewrappedBidAdapter.js index 93552638007..84b80ac14d4 100644 --- a/modules/livewrappedBidAdapter.js +++ b/modules/livewrappedBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isSafariBrowser, deepAccess, getWindowTop } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import find from 'core-js-pure/features/array/find.js'; @@ -83,7 +83,7 @@ export const spec = { gdprConsent: bidderRequest.gdprConsent ? bidderRequest.gdprConsent.consentString : undefined, coppa: getCoppa(), usPrivacy: bidderRequest.uspConsent, - cookieSupport: !utils.isSafariBrowser() && storage.cookiesAreEnabled(), + cookieSupport: !isSafariBrowser() && storage.cookiesAreEnabled(), rcv: getAdblockerRecovered(), adRequests: [...adRequests], rtbData: handleEids(bidRequests), @@ -228,11 +228,11 @@ function bidToAdRequest(bid) { adRequest.auc = bid.auc; } - adRequest.native = utils.deepAccess(bid, 'mediaTypes.native'); + adRequest.native = deepAccess(bid, 'mediaTypes.native'); - adRequest.video = utils.deepAccess(bid, 'mediaTypes.video'); + adRequest.video = deepAccess(bid, 'mediaTypes.video'); - if ((adRequest.native || adRequest.video) && utils.deepAccess(bid, 'mediaTypes.banner')) { + if ((adRequest.native || adRequest.video) && deepAccess(bid, 'mediaTypes.banner')) { adRequest.banner = true; } @@ -240,7 +240,7 @@ function bidToAdRequest(bid) { } function getSizes(bid) { - if (utils.deepAccess(bid, 'mediaTypes.banner.sizes')) { + if (deepAccess(bid, 'mediaTypes.banner.sizes')) { return bid.mediaTypes.banner.sizes; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { return bid.sizes; @@ -257,7 +257,7 @@ function sizeToFormat(size) { function getAdblockerRecovered() { try { - return utils.getWindowTop().I12C && utils.getWindowTop().I12C.Morph === 1; + return getWindowTop().I12C && getWindowTop().I12C.Morph === 1; } catch (e) {} } diff --git a/modules/liveyieldAnalyticsAdapter.js b/modules/liveyieldAnalyticsAdapter.js index d80a7067f2e..411b76a5149 100644 --- a/modules/liveyieldAnalyticsAdapter.js +++ b/modules/liveyieldAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { logError } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; const { EVENTS: { BID_REQUESTED, BID_TIMEOUT, BID_RESPONSE, BID_WON } @@ -198,7 +198,7 @@ const liveyield = Object.assign(adapter({ analyticsType: 'bundle' }), { args.bidderCode ); } catch (e) { - utils.logError(e); + logError(e); } }); break; @@ -220,7 +220,7 @@ const liveyield = Object.assign(adapter({ analyticsType: 'bundle' }), { args.statusMessage !== 'Bid available' ); } catch (e) { - utils.logError(e); + logError(e); } break; case BID_TIMEOUT: @@ -243,7 +243,7 @@ const liveyield = Object.assign(adapter({ analyticsType: 'bundle' }), { ) ); if (!ad) { - utils.logError( + logError( 'Cannot find ad by unit name: ' + liveyield.instanceConfig.getAdUnitName( liveyield.instanceConfig.getPlacementOrAdUnitCode( @@ -255,7 +255,7 @@ const liveyield = Object.assign(adapter({ analyticsType: 'bundle' }), { break; } if (!args.bidderCode || !args.cpm) { - utils.logError('Bidder code or cpm is not valid'); + logError('Bidder code or cpm is not valid'); break; } const resolution = { targetings: [] }; @@ -280,7 +280,7 @@ const liveyield = Object.assign(adapter({ analyticsType: 'bundle' }), { resolutionToUse ); } catch (e) { - utils.logError(e); + logError(e); } break; } @@ -310,27 +310,27 @@ liveyield.originEnableAnalytics = liveyield.enableAnalytics; */ liveyield.enableAnalytics = function(config) { if (!config || !config.provider || config.provider !== 'liveyield') { - utils.logError('expected config.provider to equal liveyield'); + logError('expected config.provider to equal liveyield'); return; } if (!config.options) { - utils.logError('options must be defined'); + logError('options must be defined'); return; } if (!config.options.customerId) { - utils.logError('options.customerId is required'); + logError('options.customerId is required'); return; } if (!config.options.customerName) { - utils.logError('options.customerName is required'); + logError('options.customerName is required'); return; } if (!config.options.customerSite) { - utils.logError('options.customerSite is required'); + logError('options.customerSite is required'); return; } if (!config.options.sessionTimezoneOffset) { - utils.logError('options.sessionTimezoneOffset is required'); + logError('options.sessionTimezoneOffset is required'); return; } liveyield.instanceConfig = Object.assign( @@ -340,7 +340,7 @@ liveyield.enableAnalytics = function(config) { ); if (typeof window[liveyield.instanceConfig.rtaFunctionName] !== 'function') { - utils.logError( + logError( `Function ${liveyield.instanceConfig.rtaFunctionName} is not defined.` + `Make sure that LiveYield snippet in included before the Prebid Analytics configuration.` ); diff --git a/modules/lockerdomeBidAdapter.js b/modules/lockerdomeBidAdapter.js index 4e30519c6d3..66accb4e02a 100644 --- a/modules/lockerdomeBidAdapter.js +++ b/modules/lockerdomeBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { getBidIdParameter } from '../src/utils.js'; import {BANNER} from '../src/mediaTypes.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; @@ -16,7 +16,7 @@ export const spec = { return { requestId: bid.bidId, adUnitCode: bid.adUnitCode, - adUnitId: utils.getBidIdParameter('adUnitId', bid.params), + adUnitId: getBidIdParameter('adUnitId', bid.params), sizes: bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes }; }); diff --git a/modules/loganBidAdapter.js b/modules/loganBidAdapter.js index ae6d7a344d3..75327453b2e 100644 --- a/modules/loganBidAdapter.js +++ b/modules/loganBidAdapter.js @@ -1,6 +1,6 @@ +import { isFn, deepAccess, getWindowTop } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; const BIDDER_CODE = 'logan'; @@ -25,8 +25,8 @@ function isBidResponseValid(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -50,7 +50,7 @@ export const spec = { }, buildRequests: (validBidRequests = [], bidderRequest) => { - const winTop = utils.getWindowTop(); + const winTop = getWindowTop(); const location = winTop.location; const placements = []; const request = { diff --git a/modules/lotamePanoramaIdSystem.js b/modules/lotamePanoramaIdSystem.js index 6d36687b4e8..9abebb5533c 100644 --- a/modules/lotamePanoramaIdSystem.js +++ b/modules/lotamePanoramaIdSystem.js @@ -4,7 +4,7 @@ * @module modules/lotamePanoramaId * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; +import { timestamp, isStr, logError, isBoolean, buildUrl, isEmpty, isArray } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -28,7 +28,7 @@ let cookieDomain; */ function setProfileId(profileId) { if (storage.cookiesAreEnabled()) { - let expirationDate = new Date(utils.timestamp() + NINE_MONTHS_MS).toUTCString(); + let expirationDate = new Date(timestamp() + NINE_MONTHS_MS).toUTCString(); storage.setCookie( KEY_PROFILE, profileId, @@ -88,7 +88,7 @@ function getFromStorage(key) { function saveLotameCache( key, value, - expirationTimestamp = utils.timestamp() + DAYS_TO_CACHE * DAY_MS + expirationTimestamp = timestamp() + DAYS_TO_CACHE * DAY_MS ) { if (key && value) { let expirationDate = new Date(expirationTimestamp).toUTCString(); @@ -124,11 +124,11 @@ function getLotameLocalCache() { try { const rawExpiry = getFromStorage(KEY_EXPIRY); - if (utils.isStr(rawExpiry)) { + if (isStr(rawExpiry)) { cache.expiryTimestampMs = parseInt(rawExpiry, 10); } } catch (error) { - utils.logError(error); + logError(error); } return cache; @@ -178,7 +178,7 @@ export const lotamePanoramaIdSubmodule = { * @returns {(Object|undefined)} */ decode(value, config) { - return utils.isStr(value) ? { lotamePanoramaId: value } : undefined; + return isStr(value) ? { lotamePanoramaId: value } : undefined; }, /** @@ -211,7 +211,7 @@ export const lotamePanoramaIdSubmodule = { let consentString; if (consentData) { - if (utils.isBoolean(consentData.gdprApplies)) { + if (isBoolean(consentData.gdprApplies)) { queryParams.gdpr_applies = consentData.gdprApplies; } consentString = consentData.consentString; @@ -226,11 +226,11 @@ export const lotamePanoramaIdSubmodule = { if (consentString) { queryParams.gdpr_consent = consentString; } - const url = utils.buildUrl({ + const url = buildUrl({ protocol: 'https', host: `id.crwdcntrl.net`, pathname: '/id', - search: utils.isEmpty(queryParams) ? undefined : queryParams, + search: isEmpty(queryParams) ? undefined : queryParams, }); ajax( url, @@ -240,18 +240,18 @@ export const lotamePanoramaIdSubmodule = { try { let responseObj = JSON.parse(response); const shouldUpdateProfileId = !( - utils.isArray(responseObj.errors) && + isArray(responseObj.errors) && responseObj.errors.indexOf(MISSING_CORE_CONSENT) !== -1 ); saveLotameCache(KEY_EXPIRY, responseObj.expiry_ts, responseObj.expiry_ts); - if (utils.isStr(responseObj.profile_id)) { + if (isStr(responseObj.profile_id)) { if (shouldUpdateProfileId) { setProfileId(responseObj.profile_id); } - if (utils.isStr(responseObj.core_id)) { + if (isStr(responseObj.core_id)) { saveLotameCache( KEY_ID, responseObj.core_id, @@ -268,7 +268,7 @@ export const lotamePanoramaIdSubmodule = { clearLotameCache(KEY_ID); } } catch (error) { - utils.logError(error); + logError(error); } } callback(coreId); diff --git a/modules/lunamediahbBidAdapter.js b/modules/lunamediahbBidAdapter.js index 1376d0c1714..2798eef33e4 100644 --- a/modules/lunamediahbBidAdapter.js +++ b/modules/lunamediahbBidAdapter.js @@ -1,6 +1,6 @@ +import { logMessage } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'lunamediahb'; const AD_URL = 'https://balancer.lmgssp.com/?c=o&m=multi'; @@ -38,7 +38,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; const placements = []; diff --git a/modules/madvertiseBidAdapter.js b/modules/madvertiseBidAdapter.js index 219295f0d50..457ff2409b8 100644 --- a/modules/madvertiseBidAdapter.js +++ b/modules/madvertiseBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { parseSizesInput, _each } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; @@ -15,7 +15,7 @@ export const spec = { if (typeof bid.params !== 'object') { return false; } - let sizes = utils.parseSizesInput(bid.sizes); + let sizes = parseSizesInput(bid.sizes); if (!sizes || sizes.length === 0) { return false; } @@ -46,7 +46,7 @@ export const spec = { } } - utils._each(bidRequest.params, (item, key) => src = src + '&' + key + '=' + item); + _each(bidRequest.params, (item, key) => src = src + '&' + key + '=' + item); if (typeof bidRequest.params.u == 'undefined') { src = src + '&u=' + navigator.userAgent; diff --git a/modules/marsmediaBidAdapter.js b/modules/marsmediaBidAdapter.js index bb1763ebb2e..79e2148084a 100644 --- a/modules/marsmediaBidAdapter.js +++ b/modules/marsmediaBidAdapter.js @@ -1,6 +1,6 @@ -'use strict'; -import * as utils from '../src/utils.js'; +'use strict'; +import { deepAccess, getDNT, parseSizesInput, isArray, getWindowTop, deepSetValue, triggerPixel, getWindowSelf } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -42,13 +42,13 @@ function MarsmediaAdapter() { impObj.id = BRs[i].adUnitCode; impObj.secure = isSecure; - if (utils.deepAccess(BRs[i], 'mediaTypes.banner') || utils.deepAccess(BRs[i], 'mediaType') === 'banner') { + if (deepAccess(BRs[i], 'mediaTypes.banner') || deepAccess(BRs[i], 'mediaType') === 'banner') { let banner = frameBanner(BRs[i]); if (banner) { impObj.banner = banner; } } - if (utils.deepAccess(BRs[i], 'mediaTypes.video') || utils.deepAccess(BRs[i], 'mediaType') === 'video') { + if (deepAccess(BRs[i], 'mediaTypes.video') || deepAccess(BRs[i], 'mediaType') === 'video') { impObj.video = frameVideo(BRs[i]); } if (!(impObj.banner || impObj.video)) { @@ -87,7 +87,7 @@ function MarsmediaAdapter() { return { ua: navigator.userAgent, ip: '', // Empty Ip string is required, server gets the ip from HTTP header - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, } } @@ -107,7 +107,7 @@ function MarsmediaAdapter() { if (adUnit.mediaTypes && adUnit.mediaTypes.banner) { sizeList = adUnit.mediaTypes.banner.sizes; } - var sizeStringList = utils.parseSizesInput(sizeList); + var sizeStringList = parseSizesInput(sizeList); var format = []; sizeStringList.forEach(function(size) { if (size) { @@ -131,9 +131,9 @@ function MarsmediaAdapter() { function frameVideo(bid) { var size = []; - if (utils.deepAccess(bid, 'mediaTypes.video.playerSize')) { + if (deepAccess(bid, 'mediaTypes.video.playerSize')) { var dimensionSet = bid.mediaTypes.video.playerSize; - if (utils.isArray(bid.mediaTypes.video.playerSize[0])) { + if (isArray(bid.mediaTypes.video.playerSize[0])) { dimensionSet = bid.mediaTypes.video.playerSize[0]; } var validSize = getValidSizeSet(dimensionSet) @@ -142,29 +142,29 @@ function MarsmediaAdapter() { } } return { - mimes: utils.deepAccess(bid, 'mediaTypes.video.mimes') || SUPPORTED_VIDEO_MIMES, - protocols: utils.deepAccess(bid, 'mediaTypes.video.protocols') || SUPPORTED_VIDEO_PROTOCOLS, + mimes: deepAccess(bid, 'mediaTypes.video.mimes') || SUPPORTED_VIDEO_MIMES, + protocols: deepAccess(bid, 'mediaTypes.video.protocols') || SUPPORTED_VIDEO_PROTOCOLS, w: size[0], h: size[1], - startdelay: utils.deepAccess(bid, 'mediaTypes.video.startdelay') || 0, - skip: utils.deepAccess(bid, 'mediaTypes.video.skip') || 0, - playbackmethod: utils.deepAccess(bid, 'mediaTypes.video.playbackmethod') || SUPPORTED_VIDEO_PLAYBACK_METHODS, - delivery: utils.deepAccess(bid, 'mediaTypes.video.delivery') || SUPPORTED_VIDEO_DELIVERY, - api: utils.deepAccess(bid, 'mediaTypes.video.api') || SUPPORTED_VIDEO_API, + startdelay: deepAccess(bid, 'mediaTypes.video.startdelay') || 0, + skip: deepAccess(bid, 'mediaTypes.video.skip') || 0, + playbackmethod: deepAccess(bid, 'mediaTypes.video.playbackmethod') || SUPPORTED_VIDEO_PLAYBACK_METHODS, + delivery: deepAccess(bid, 'mediaTypes.video.delivery') || SUPPORTED_VIDEO_DELIVERY, + api: deepAccess(bid, 'mediaTypes.video.api') || SUPPORTED_VIDEO_API, } } function frameExt(bid) { if ((bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes)) { let bidSizes = (bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes) || bid.sizes; - bidSizes = ((utils.isArray(bidSizes) && utils.isArray(bidSizes[0])) ? bidSizes : [bidSizes]); - bidSizes = bidSizes.filter(size => utils.isArray(size)); + bidSizes = ((isArray(bidSizes) && isArray(bidSizes[0])) ? bidSizes : [bidSizes]); + bidSizes = bidSizes.filter(size => isArray(size)); const processedSizes = bidSizes.map(size => ({w: parseInt(size[0], 10), h: parseInt(size[1], 10)})); const element = document.getElementById(bid.adUnitCode); const minSize = _getMinSize(processedSizes); const viewabilityAmount = _isViewabilityMeasurable(element) - ? _getViewability(element, utils.getWindowTop(), minSize) + ? _getViewability(element, getWindowTop(), minSize) : 'na'; const viewabilityAmountRounded = isNaN(viewabilityAmount) ? viewabilityAmount : Math.round(viewabilityAmount); @@ -192,25 +192,25 @@ function MarsmediaAdapter() { device: frameDevice(), user: { ext: { - consent: utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? bidderRequest.gdprConsent.consentString : '' + consent: deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? bidderRequest.gdprConsent.consentString : '' } }, at: 1, tmax: 650, regs: { ext: { - gdpr: utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? Boolean(bidderRequest.gdprConsent.gdprApplies & 1) : false + gdpr: deepAccess(bidderRequest, 'gdprConsent.gdprApplies') ? Boolean(bidderRequest.gdprConsent.gdprApplies & 1) : false } } }; if (BRs[0].schain) { - utils.deepSetValue(bid, 'source.ext.schain', BRs[0].schain); + deepSetValue(bid, 'source.ext.schain', BRs[0].schain); } if (bidderRequest.uspConsent) { - utils.deepSetValue(bid, 'regs.ext.us_privacy', bidderRequest.uspConsent) + deepSetValue(bid, 'regs.ext.us_privacy', bidderRequest.uspConsent) } if (config.getConfig('coppa') === true) { - utils.deepSetValue(bid, 'regs.coppa', config.getConfig('coppa') & 1) + deepSetValue(bid, 'regs.coppa', config.getConfig('coppa') & 1) } return bid; @@ -255,7 +255,7 @@ function MarsmediaAdapter() { /\$\{AUCTION_PRICE\}/, cpm ); - utils.triggerPixel(bid.nurl, null); + triggerPixel(bid.nurl, null); }; sendbeacon(bid, 17) }; @@ -320,7 +320,7 @@ function MarsmediaAdapter() { function sendbeacon(bid, type) { const bidString = JSON.stringify(bid); const encodedBuf = window.btoa(bidString); - utils.triggerPixel('https://ping-hqx-1.go2speed.media/notification/rtb/beacon/?bt=' + type + '&bid=3mhdom&hb_j=' + encodedBuf, null); + triggerPixel('https://ping-hqx-1.go2speed.media/notification/rtb/beacon/?bt=' + type + '&bid=3mhdom&hb_j=' + encodedBuf, null); } /** @@ -359,7 +359,7 @@ function MarsmediaAdapter() { function _isIframe() { try { - return utils.getWindowSelf() !== utils.getWindowTop(); + return getWindowSelf() !== getWindowTop(); } catch (e) { return true; } diff --git a/modules/mathildeadsBidAdapter.js b/modules/mathildeadsBidAdapter.js index 096b655c3be..3f5d94f0df2 100644 --- a/modules/mathildeadsBidAdapter.js +++ b/modules/mathildeadsBidAdapter.js @@ -1,6 +1,6 @@ +import { isFn, deepAccess, logMessage } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; const BIDDER_CODE = 'mathildeads'; @@ -71,8 +71,8 @@ function getPlacementReqData (bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -121,7 +121,7 @@ export const spec = { deviceHeight = winTop.screen.height; winLocation = winTop.location; } catch (e) { - utils.logMessage(e); + logMessage(e); winLocation = window.location; } @@ -130,7 +130,7 @@ export const spec = { try { refferLocation = refferUrl && new URL(refferUrl); } catch (e) { - utils.logMessage(e); + logMessage(e); } let location = refferLocation || winLocation; diff --git a/modules/mediaforceBidAdapter.js b/modules/mediaforceBidAdapter.js index 4c303ea9b37..7d4f22b7916 100644 --- a/modules/mediaforceBidAdapter.js +++ b/modules/mediaforceBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { getDNT, deepAccess, isStr, replaceAuctionPrice, triggerPixel, parseGPTSingleSizeArrayToRtbSize, isEmpty } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, NATIVE} from '../src/mediaTypes.js'; @@ -116,7 +116,7 @@ export const spec = { const referer = bidderRequest && bidderRequest.refererInfo ? encodeURIComponent(bidderRequest.refererInfo.referer) : ''; const auctionId = bidderRequest && bidderRequest.auctionId; const timeout = bidderRequest && bidderRequest.timeout; - const dnt = utils.getDNT() ? 1 : 0; + const dnt = getDNT() ? 1 : 0; const requestsMap = {}; const requests = []; let isTest = false; @@ -260,10 +260,10 @@ export const spec = { * @param {Bid} The bid that won the auction */ onBidWon: function(bid) { - const cpm = utils.deepAccess(bid, 'adserverTargeting.hb_pb') || ''; - if (utils.isStr(bid.burl) && bid.burl !== '') { - bid.burl = utils.replaceAuctionPrice(bid.burl, cpm); - utils.triggerPixel(bid.burl); + const cpm = deepAccess(bid, 'adserverTargeting.hb_pb') || ''; + if (isStr(bid.burl) && bid.burl !== '') { + bid.burl = replaceAuctionPrice(bid.burl, cpm); + triggerPixel(bid.burl); } }, }; @@ -280,9 +280,9 @@ function createBannerRequest(bid) { if (!sizes.length) return; let format = []; - let r = utils.parseGPTSingleSizeArrayToRtbSize(sizes[0]); + let r = parseGPTSingleSizeArrayToRtbSize(sizes[0]); for (let f = 1; f < sizes.length; f++) { - format.push(utils.parseGPTSingleSizeArrayToRtbSize(sizes[f])); + format.push(parseGPTSingleSizeArrayToRtbSize(sizes[f])); } if (format.length) { r.format = format @@ -303,15 +303,15 @@ function parseNative(native) { const {id, img, data, title} = asset; const key = NATIVE_ID_MAP[id]; if (key) { - if (!utils.isEmpty(title)) { + if (!isEmpty(title)) { result.title = title.text - } else if (!utils.isEmpty(img)) { + } else if (!isEmpty(img)) { result[key] = { url: img.url, height: img.h, width: img.w } - } else if (!utils.isEmpty(data)) { + } else if (!isEmpty(data)) { result[key] = data.value; } } From f4f634d0c1162cfe71350247c7764f3edc6dd029 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Mon, 27 Sep 2021 13:23:06 -0700 Subject: [PATCH 22/84] Multiple Bid/Analytics/ID Adapters: import utils functions as needed and not the whole module (#7479) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/apacdexBidAdapter.js | 32 ++++----- modules/appnexusBidAdapter.js | 118 +++++++++++++++---------------- modules/apstreamBidAdapter.js | 10 +-- modules/asoBidAdapter.js | 60 ++++++++-------- modules/astraoneBidAdapter.js | 4 +- modules/atsAnalyticsAdapter.js | 22 +++--- modules/audiencerunBidAdapter.js | 30 ++++---- modules/automatadBidAdapter.js | 4 +- modules/axonixBidAdapter.js | 14 ++-- modules/beachfrontBidAdapter.js | 46 ++++++------ modules/beopBidAdapter.js | 44 ++++++------ modules/bidViewabilityIO.js | 14 ++-- modules/bidglassBidAdapter.js | 16 ++--- modules/bidscubeBidAdapter.js | 6 +- modules/bizzclickBidAdapter.js | 20 +++--- 15 files changed, 220 insertions(+), 220 deletions(-) diff --git a/modules/apacdexBidAdapter.js b/modules/apacdexBidAdapter.js index 6c1c350b800..421eb99b4c1 100644 --- a/modules/apacdexBidAdapter.js +++ b/modules/apacdexBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isPlainObject, isArray, replaceAuctionPrice, isFn } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'apacdex'; @@ -32,16 +32,16 @@ export const spec = { if (!bid.params.siteId && !bid.params.placementId) { return false; } - if (!utils.deepAccess(bid, 'mediaTypes.banner') && !utils.deepAccess(bid, 'mediaTypes.video')) { + if (!deepAccess(bid, 'mediaTypes.banner') && !deepAccess(bid, 'mediaTypes.video')) { return false; } - if (utils.deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video - if (!utils.deepAccess(bid, 'mediaTypes.banner.sizes')) { + if (deepAccess(bid, 'mediaTypes.banner')) { // Not support multi type bids, favor banner over video + if (!deepAccess(bid, 'mediaTypes.banner.sizes')) { // sizes at the banner is required. return false; } - } else if (utils.deepAccess(bid, 'mediaTypes.video')) { - if (!utils.deepAccess(bid, 'mediaTypes.video.playerSize')) { + } else if (deepAccess(bid, 'mediaTypes.video')) { + if (!deepAccess(bid, 'mediaTypes.video.playerSize')) { // playerSize is required for instream adUnits. return false; } @@ -170,12 +170,12 @@ export const spec = { }, interpretResponse: function (serverResponse, bidRequest) { const serverBody = serverResponse.body; - if (!serverBody || !utils.isPlainObject(serverBody)) { + if (!serverBody || !isPlainObject(serverBody)) { return []; } const serverBids = serverBody.bids; - if (!serverBids || !utils.isArray(serverBids)) { + if (!serverBids || !isArray(serverBids)) { return []; } @@ -197,12 +197,12 @@ export const spec = { bidResponse.dealId = dealId; } if (bid.vastXml) { - bidResponse.vastXml = utils.replaceAuctionPrice(bid.vastXml, bid.cpm); + bidResponse.vastXml = replaceAuctionPrice(bid.vastXml, bid.cpm); } else { - bidResponse.ad = utils.replaceAuctionPrice(bid.ad, bid.cpm); + bidResponse.ad = replaceAuctionPrice(bid.ad, bid.cpm); } bidResponse.meta = {}; - if (bid.meta && bid.meta.advertiserDomains && utils.isArray(bid.meta.advertiserDomains)) { + if (bid.meta && bid.meta.advertiserDomains && isArray(bid.meta.advertiserDomains)) { bidResponse.meta.advertiserDomains = bid.meta.advertiserDomains; } bidResponses.push(bidResponse); @@ -285,7 +285,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { if (config.getConfig('pageUrl')) { return config.getConfig('pageUrl'); } - if (utils.deepAccess(bidderRequest, 'refererInfo.referer')) { + if (deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -303,7 +303,7 @@ function _extractTopWindowUrlFromBidderRequest(bidderRequest) { * @returns {string} */ function _extractTopWindowReferrerFromBidderRequest(bidderRequest) { - if (bidderRequest && utils.deepAccess(bidderRequest, 'refererInfo.referer')) { + if (bidderRequest && deepAccess(bidderRequest, 'refererInfo.referer')) { return bidderRequest.refererInfo.referer; } @@ -340,7 +340,7 @@ export function getDomain(pageUrl) { * @returns {boolean} */ export function validateGeoObject(geo) { - if (!utils.isPlainObject(geo)) { + if (!isPlainObject(geo)) { return false; } if (!geo.lat) { @@ -362,7 +362,7 @@ export function validateGeoObject(geo) { * @returns {float||null} */ function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.floorPrice) ? bid.params.floorPrice : null; } @@ -371,7 +371,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/appnexusBidAdapter.js b/modules/appnexusBidAdapter.js index 9882e71fe4f..7dcbd74d779 100644 --- a/modules/appnexusBidAdapter.js +++ b/modules/appnexusBidAdapter.js @@ -1,5 +1,5 @@ +import { convertCamelToUnderscore, isArray, isNumber, isPlainObject, logError, logInfo, deepAccess, logMessage, convertTypes, isStr, getParameterByName, deepClone, chunk, logWarn, getBidRequest, createTrackPixelHtml, isEmpty, transformBidderParamKeywords, getMaxValueFromArray, fill, getMinValueFromArray, isArrayOfNums, isFn } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder, getIabSubCategory } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO, ADPOD } from '../src/mediaTypes.js'; @@ -109,13 +109,13 @@ export const spec = { Object.keys(userObjBid.params.user) .filter(param => includes(USER_PARAMS, param)) .forEach((param) => { - let uparam = utils.convertCamelToUnderscore(param); - if (param === 'segments' && utils.isArray(userObjBid.params.user[param])) { + let uparam = convertCamelToUnderscore(param); + if (param === 'segments' && isArray(userObjBid.params.user[param])) { let segs = []; userObjBid.params.user[param].forEach(val => { - if (utils.isNumber(val)) { + if (isNumber(val)) { segs.push({'id': val}); - } else if (utils.isPlainObject(val)) { + } else if (isPlainObject(val)) { segs.push(val); } }); @@ -152,7 +152,7 @@ export const spec = { try { debugObj = JSON.parse(debugCookie); } catch (e) { - utils.logError('AppNexus Debug Auction Cookie Error:\n\n' + e); + logError('AppNexus Debug Auction Cookie Error:\n\n' + e); } } else { const debugBidRequest = find(bidRequests, hasDebug); @@ -208,7 +208,7 @@ export const spec = { if (debugObjParams.enabled) { payload.debug = debugObjParams; - utils.logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); + logInfo('AppNexus Debug Auction Settings:\n\n' + JSON.stringify(debugObjParams, null, 4)); } if (bidderRequest && bidderRequest.gdprConsent) { @@ -253,12 +253,12 @@ export const spec = { if (bidRequests[0].userId) { let eids = []; - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); - addUserId(eids, utils.deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); + addUserId(eids, deepAccess(bidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.netId`), 'netid.de', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.idl_env`), 'liveramp.com', null); + addUserId(eids, deepAccess(bidRequests[0], `userId.tdid`), 'adserver.org', 'TDID'); + addUserId(eids, deepAccess(bidRequests[0], `userId.uid2.id`), 'uidapi.com', 'UID2'); if (eids.length) { payload.eids = eids; @@ -285,7 +285,7 @@ export const spec = { if (!serverResponse || serverResponse.error) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; } - utils.logError(errorMessage); + logError(errorMessage); return bids; } @@ -313,8 +313,8 @@ export const spec = { .replace(/

(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1 .replace(/(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags - utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); - utils.logMessage(debugText); + logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction'); + logMessage(debugText); } return bids; @@ -348,11 +348,11 @@ export const spec = { }, transformBidParams: function (params, isOpenRtb) { - params = utils.convertTypes({ + params = convertTypes({ 'member': 'string', 'invCode': 'string', 'placementId': 'number', - 'keywords': utils.transformBidderParamKeywords, + 'keywords': transformBidderParamKeywords, 'publisherId': 'number' }, params); @@ -365,7 +365,7 @@ export const spec = { } Object.keys(params).forEach(paramKey => { - let convertedKey = utils.convertCamelToUnderscore(paramKey); + let convertedKey = convertCamelToUnderscore(paramKey); if (convertedKey !== paramKey) { params[convertedKey] = params[paramKey]; delete params[paramKey]; @@ -388,7 +388,7 @@ export const spec = { } function isPopulatedArray(arr) { - return !!(utils.isArray(arr) && arr.length > 0); + return !!(isArray(arr) && arr.length > 0); } function deleteValues(keyPairObj) { @@ -460,9 +460,9 @@ function strIsAppnexusViewabilityScript(str) { function getAppnexusViewabilityScriptFromJsTrackers(jsTrackerArray) { let viewJsPayload; - if (utils.isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { + if (isStr(jsTrackerArray) && strIsAppnexusViewabilityScript(jsTrackerArray)) { viewJsPayload = jsTrackerArray; - } else if (utils.isArray(jsTrackerArray)) { + } else if (isArray(jsTrackerArray)) { for (let i = 0; i < jsTrackerArray.length; i++) { let currentJsTracker = jsTrackerArray[i]; if (strIsAppnexusViewabilityScript(currentJsTracker)) { @@ -486,7 +486,7 @@ function hasPurpose1Consent(bidderRequest) { let result = true; if (bidderRequest && bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { - result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -504,16 +504,16 @@ function formatRequest(payload, bidderRequest) { endpointUrl = URL_SIMPLE; } - if (utils.getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { + if (getParameterByName('apn_test').toUpperCase() === 'TRUE' || config.getConfig('apn_test') === true) { options.customHeaders = { 'X-Is-Test': 1 } } if (payload.tags.length > MAX_IMPS_PER_REQUEST) { - const clonedPayload = utils.deepClone(payload); + const clonedPayload = deepClone(payload); - utils.chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { + chunk(payload.tags, MAX_IMPS_PER_REQUEST).forEach(tags => { clonedPayload.tags = tags; const payloadString = JSON.stringify(clonedPayload); request.push({ @@ -550,14 +550,14 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } renderer.setEventHandlers({ - impression: () => utils.logMessage('AppNexus outstream video impression event'), - loaded: () => utils.logMessage('AppNexus outstream video loaded event'), + impression: () => logMessage('AppNexus outstream video impression event'), + loaded: () => logMessage('AppNexus outstream video loaded event'), ended: () => { - utils.logMessage('AppNexus outstream renderer video event'); + logMessage('AppNexus outstream renderer video event'); document.querySelector(`#${adUnitCode}`).style.display = 'none'; } }); @@ -572,7 +572,7 @@ function newRenderer(adUnitCode, rtbBid, rendererOptions = {}) { * @return Bid */ function newBid(serverBid, rtbBid, bidderRequest) { - const bidRequest = utils.getBidRequest(serverBid.uuid, [bidderRequest]); + const bidRequest = getBidRequest(serverBid.uuid, [bidderRequest]); const bid = { requestId: serverBid.uuid, cpm: rtbBid.cpm, @@ -607,7 +607,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { ttl: 3600 }); - const videoContext = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const videoContext = deepAccess(bidRequest, 'mediaTypes.video.context'); switch (videoContext) { case ADPOD: const primaryCatId = getIabSubCategory(bidRequest.bidder, rtbBid.brand_category_id); @@ -628,7 +628,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (rtbBid.renderer_url) { const videoBid = find(bidderRequest.bids, bid => bid.bidId === serverBid.uuid); - const rendererOptions = utils.deepAccess(videoBid, 'renderer.options'); + const rendererOptions = deepAccess(videoBid, 'renderer.options'); bid.renderer = newRenderer(bid.adUnitCode, rtbBid, rendererOptions); } break; @@ -648,7 +648,7 @@ function newBid(serverBid, rtbBid, bidderRequest) { if (jsTrackers == undefined) { jsTrackers = jsTrackerDisarmed; - } else if (utils.isStr(jsTrackers)) { + } else if (isStr(jsTrackers)) { jsTrackers = [jsTrackers, jsTrackerDisarmed]; } else { jsTrackers.push(jsTrackerDisarmed); @@ -697,11 +697,11 @@ function newBid(serverBid, rtbBid, bidderRequest) { try { if (rtbBid.rtb.trackers) { const url = rtbBid.rtb.trackers[0].impression_urls[0]; - const tracker = utils.createTrackPixelHtml(url); + const tracker = createTrackPixelHtml(url); bid.ad += tracker; } } catch (error) { - utils.logError('Error appending tracking pixel', error); + logError('Error appending tracking pixel', error); } } @@ -751,8 +751,8 @@ function bidToTag(bid) { if (bid.params.externalImpId) { tag.external_imp_id = bid.params.externalImpId; } - if (!utils.isEmpty(bid.params.keywords)) { - let keywords = utils.transformBidderParamKeywords(bid.params.keywords); + if (!isEmpty(bid.params.keywords)) { + let keywords = transformBidderParamKeywords(bid.params.keywords); if (keywords.length > 0) { keywords.forEach(deleteValues); @@ -760,12 +760,12 @@ function bidToTag(bid) { tag.keywords = keywords; } - let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { tag.gpid = gpid; } - if (bid.mediaType === NATIVE || utils.deepAccess(bid, `mediaTypes.${NATIVE}`)) { + if (bid.mediaType === NATIVE || deepAccess(bid, `mediaTypes.${NATIVE}`)) { tag.ad_types.push(NATIVE); if (tag.sizes.length === 0) { tag.sizes = transformSizes([1, 1]); @@ -777,8 +777,8 @@ function bidToTag(bid) { } } - const videoMediaType = utils.deepAccess(bid, `mediaTypes.${VIDEO}`); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, `mediaTypes.${VIDEO}`); + const context = deepAccess(bid, 'mediaTypes.video.context'); if (videoMediaType && context === 'adpod') { tag.hb_source = 7; @@ -804,7 +804,7 @@ function bidToTag(bid) { case 'context': case 'playback_method': let type = bid.params.video[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; tag.video[param] = VIDEO_MAPPING[param][type]; break; // Deprecating tags[].video.frameworks in favor of tags[].video_frameworks @@ -815,7 +815,7 @@ function bidToTag(bid) { } }); - if (bid.params.video.frameworks && utils.isArray(bid.params.video.frameworks)) { + if (bid.params.video.frameworks && isArray(bid.params.video.frameworks)) { tag['video_frameworks'] = bid.params.video.frameworks; } } @@ -840,7 +840,7 @@ function bidToTag(bid) { case 'playbackmethod': if (typeof tag.video['playback_method'] !== 'number') { let type = videoMediaType[param]; - type = (utils.isArray(type)) ? type[0] : type; + type = (isArray(type)) ? type[0] : type; // we only support iab's options 1-4 at this time. if (type >= 1 && type <= 4) { @@ -849,7 +849,7 @@ function bidToTag(bid) { } break; case 'api': - if (!tag['video_frameworks'] && utils.isArray(videoMediaType[param])) { + if (!tag['video_frameworks'] && isArray(videoMediaType[param])) { // need to read thru array; remove 6 (we don't support it), swap 4 <> 5 if found (to match our adserver mapping for these specific values) let apiTmp = videoMediaType[param].map(val => { let v = (val === 4) ? 5 : (val === 5) ? 4 : val; @@ -869,7 +869,7 @@ function bidToTag(bid) { tag.video = Object.assign({}, tag.video, { custom_renderer_present: true }); } - if (bid.params.frameworks && utils.isArray(bid.params.frameworks)) { + if (bid.params.frameworks && isArray(bid.params.frameworks)) { tag['banner_frameworks'] = bid.params.frameworks; } @@ -890,8 +890,8 @@ function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; - if (utils.isArray(requestSizes) && requestSizes.length === 2 && - !utils.isArray(requestSizes[0])) { + if (isArray(requestSizes) && requestSizes.length === 2 && + !isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); @@ -945,10 +945,10 @@ function hasOmidSupport(bid) { let hasOmid = false; const bidderParams = bid.params; const videoParams = bid.params.video; - if (bidderParams.frameworks && utils.isArray(bidderParams.frameworks)) { + if (bidderParams.frameworks && isArray(bidderParams.frameworks)) { hasOmid = includes(bid.params.frameworks, 6); } - if (!hasOmid && videoParams && videoParams.frameworks && utils.isArray(videoParams.frameworks)) { + if (!hasOmid && videoParams && videoParams.frameworks && isArray(videoParams.frameworks)) { hasOmid = includes(bid.params.video.frameworks, 6); } return hasOmid; @@ -963,14 +963,14 @@ function createAdPodRequest(tags, adPodBid) { const { durationRangeSec, requireExactDuration } = adPodBid.mediaTypes.video; const numberOfPlacements = getAdPodPlacementNumber(adPodBid.mediaTypes.video); - const maxDuration = utils.getMaxValueFromArray(durationRangeSec); + const maxDuration = getMaxValueFromArray(durationRangeSec); const tagToDuplicate = tags.filter(tag => tag.uuid === adPodBid.bidId); - let request = utils.fill(...tagToDuplicate, numberOfPlacements); + let request = fill(...tagToDuplicate, numberOfPlacements); if (requireExactDuration) { const divider = Math.ceil(numberOfPlacements / durationRangeSec.length); - const chunked = utils.chunk(request, divider); + const chunked = chunk(request, divider); // each configured duration is set as min/maxduration for a subset of requests durationRangeSec.forEach((duration, index) => { @@ -989,7 +989,7 @@ function createAdPodRequest(tags, adPodBid) { function getAdPodPlacementNumber(videoParams) { const { adPodDurationSec, durationRangeSec, requireExactDuration } = videoParams; - const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec); + const minAllowedDuration = getMinValueFromArray(durationRangeSec); const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration); return requireExactDuration @@ -998,7 +998,7 @@ function getAdPodPlacementNumber(videoParams) { } function setVideoProperty(tag, key, value) { - if (utils.isEmpty(tag.video)) { tag.video = {}; } + if (isEmpty(tag.video)) { tag.video = {}; } tag.video[key] = value; } @@ -1029,7 +1029,7 @@ function buildNativeRequest(params) { const isImageAsset = !!(requestKey === NATIVE_MAPPING.image.serverName || requestKey === NATIVE_MAPPING.icon.serverName); if (isImageAsset && request[requestKey].sizes) { let sizes = request[requestKey].sizes; - if (utils.isArrayOfNums(sizes) || (utils.isArray(sizes) && sizes.length > 0 && sizes.every(sz => utils.isArrayOfNums(sz)))) { + if (isArrayOfNums(sizes) || (isArray(sizes) && sizes.length > 0 && sizes.every(sz => isArrayOfNums(sz)))) { request[requestKey].sizes = transformSizes(request[requestKey].sizes); } } @@ -1108,7 +1108,7 @@ function addUserId(eids, id, source, rti) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.reserve) ? bid.params.reserve : null; } @@ -1117,7 +1117,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/apstreamBidAdapter.js b/modules/apstreamBidAdapter.js index 4fb89b9c720..f2d4189f237 100644 --- a/modules/apstreamBidAdapter.js +++ b/modules/apstreamBidAdapter.js @@ -1,6 +1,6 @@ +import { generateUUID, deepAccess, createTrackPixelHtml, getDNT } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { getStorageManager } from '../src/storageManager.js'; const CONSTANTS = { @@ -221,7 +221,7 @@ var dsuModule = (function() { } function generateDsu() { - var dsuId = utils.generateUUID(); + var dsuId = generateUUID(); var loc = location(); var dsuIdSuffix = hashWithKey(dsuId + loc.toString()); @@ -303,7 +303,7 @@ function getConsentStringFromPrebid(gdprConsentConfig) { } function getIabConsentString(bidderRequest) { - if (utils.deepAccess(bidderRequest, 'gdprConsent')) { + if (deepAccess(bidderRequest, 'gdprConsent')) { return getConsentStringFromPrebid(bidderRequest.gdprConsent); } @@ -318,7 +318,7 @@ function injectPixels(ad, pixels, scripts) { let trackedAd = ad; if (pixels) { pixels.forEach(pixel => { - const tracker = utils.createTrackPixelHtml(pixel); + const tracker = createTrackPixelHtml(pixel); trackedAd += tracker; }); } @@ -420,7 +420,7 @@ function buildRequests(bidRequests, bidderRequest) { med: encodeURIComponent(window.location.href), auid: bidderRequest.auctionId, ref: document.referrer, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, sr: getScreenParams() }; diff --git a/modules/asoBidAdapter.js b/modules/asoBidAdapter.js index 8f06b8ed856..bf45b9ee48f 100644 --- a/modules/asoBidAdapter.js +++ b/modules/asoBidAdapter.js @@ -1,5 +1,5 @@ +import { _each, deepAccess, logWarn, tryAppendQueryString, inIframe, getWindowTop, parseUrl, parseSizesInput, isFn, getDNT, deepSetValue } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {Renderer} from '../src/Renderer.js'; @@ -22,16 +22,16 @@ export const spec = { buildRequests: (validBidRequests, bidderRequest) => { let serverRequests = []; - utils._each(validBidRequests, bidRequest => { + _each(validBidRequests, bidRequest => { const payload = createBasePayload(bidRequest, bidderRequest); - const bannerParams = utils.deepAccess(bidRequest, 'mediaTypes.banner'); - const videoParams = utils.deepAccess(bidRequest, 'mediaTypes.video'); + const bannerParams = deepAccess(bidRequest, 'mediaTypes.banner'); + const videoParams = deepAccess(bidRequest, 'mediaTypes.video'); let imp; if (bannerParams && videoParams) { - utils.logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') + logWarn('Please note, multiple mediaTypes are not supported. The only banner will be used.') } if (bannerParams) { @@ -93,7 +93,7 @@ export const spec = { bid.ad = serverBid.adm; } else if (bid.mediaType === VIDEO) { bid.vastXml = serverBid.adm; - if (utils.deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { + if (deepAccess(bidRequest, 'mediaTypes.video.context') === 'outstream') { bid.adResponse = { content: bid.vastXml, }; @@ -112,25 +112,25 @@ export const spec = { if (serverResponses && serverResponses.length !== 0) { let query = ''; if (gdprConsent) { - query = utils.tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); - query = utils.tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); + query = tryAppendQueryString(query, 'gdpr', (gdprConsent.gdprApplies ? 1 : 0)); + query = tryAppendQueryString(query, 'consents_str', gdprConsent.consentString); const consentsIds = getConsentsIds(gdprConsent); if (consentsIds) { - query = utils.tryAppendQueryString(query, 'consents', consentsIds); + query = tryAppendQueryString(query, 'consents', consentsIds); } } if (uspConsent) { - query = utils.tryAppendQueryString(query, 'us_privacy', uspConsent); + query = tryAppendQueryString(query, 'us_privacy', uspConsent); } - utils._each(serverResponses, resp => { - const userSyncs = utils.deepAccess(resp, 'body.ext.user_syncs'); + _each(serverResponses, resp => { + const userSyncs = deepAccess(resp, 'body.ext.user_syncs'); if (!userSyncs) { return; } - utils._each(userSyncs, us => { + _each(userSyncs, us => { urls.push({ type: us.type, url: us.url + (query ? '?' + query : '') @@ -159,7 +159,7 @@ function createRenderer(bid, url) { id: bid.bidId, url: url, loaded: false, - config: utils.deepAccess(bid, 'renderer.options'), + config: deepAccess(bid, 'renderer.options'), adUnitCode: bid.adUnitCode }); renderer.setRender(outstreamRender); @@ -172,16 +172,16 @@ function getUrlsInfo(bidderRequest) { const {refererInfo} = bidderRequest; - if (utils.inIframe()) { + if (inIframe()) { page = refererInfo.referer; } else { - const w = utils.getWindowTop(); + const w = getWindowTop(); page = w.location.href; referrer = w.document.referrer || ''; } page = config.getConfig('pageUrl') || page; - const url = utils.parseUrl(page); + const url = parseUrl(page); const domain = url.hostname; return { @@ -192,7 +192,7 @@ function getUrlsInfo(bidderRequest) { } function getSize(paramSizes) { - const parsedSizes = utils.parseSizesInput(paramSizes); + const parsedSizes = parseSizesInput(paramSizes); const sizes = parsedSizes.map(size => { const [width, height] = size.split('x'); const w = parseInt(width, 10); @@ -204,7 +204,7 @@ function getSize(paramSizes) { } function getBidFloor(bidRequest, size) { - if (!utils.isFn(bidRequest.getFloor)) { + if (!isFn(bidRequest.getFloor)) { return null; } @@ -245,7 +245,7 @@ function createBannerImp(bidRequest, bannerParams) { imp.banner = { w: size.w, h: size.h, - topframe: utils.inIframe() ? 0 : 1 + topframe: inIframe() ? 0 : 1 } return imp; @@ -284,7 +284,7 @@ function getEnpoint(bidRequest) { } function getConsentsIds(gdprConsent) { - const consents = utils.deepAccess(gdprConsent, 'vendorData.purpose.consents', []); + const consents = deepAccess(gdprConsent, 'vendorData.purpose.consents', []); let consentsIds = []; Object.keys(consents).forEach(function (key) { @@ -310,7 +310,7 @@ function createBasePayload(bidRequest, bidderRequest) { ref: urlsInfo.referrer }, device: { - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, h: window.innerHeight, w: window.innerWidth, }, @@ -320,29 +320,29 @@ function createBasePayload(bidRequest, bidderRequest) { }; if (bidRequest.params.attr) { - utils.deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); + deepSetValue(payload, 'site.ext.attr', bidRequest.params.attr); } if (bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); const consentsIds = getConsentsIds(bidderRequest.gdprConsent); if (consentsIds) { - utils.deepSetValue(payload, 'user.ext.consents', consentsIds); + deepSetValue(payload, 'user.ext.consents', consentsIds); } - utils.deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); + deepSetValue(payload, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1); } if (bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (config.getConfig('coppa')) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } - const eids = utils.deepAccess(bidRequest, 'userIdAsEids'); + const eids = deepAccess(bidRequest, 'userIdAsEids'); if (eids && eids.length) { - utils.deepSetValue(payload, 'user.ext.eids', eids); + deepSetValue(payload, 'user.ext.eids', eids); } return payload; diff --git a/modules/astraoneBidAdapter.js b/modules/astraoneBidAdapter.js index 2fec3892d27..c233e665499 100644 --- a/modules/astraoneBidAdapter.js +++ b/modules/astraoneBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js' +import { _map } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER } from '../src/mediaTypes.js' @@ -7,7 +7,7 @@ const SSP_ENDPOINT = 'https://ssp.astraone.io/auction/prebid'; const TTL = 60; function buildBidRequests(validBidRequests) { - return utils._map(validBidRequests, function(validBidRequest) { + return _map(validBidRequests, function(validBidRequest) { const params = validBidRequest.params; const bidRequest = { bidId: validBidRequest.bidId, diff --git a/modules/atsAnalyticsAdapter.js b/modules/atsAnalyticsAdapter.js index 0cff7bbd68f..df293556a4c 100644 --- a/modules/atsAnalyticsAdapter.js +++ b/modules/atsAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { logError, logInfo } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -256,7 +256,7 @@ export function parseBrowser() { let browserName = result && result.length ? result[0].name : ''; return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown'; } catch (err) { - utils.logError('ATS Analytics - Error while checking user browser!', err); + logError('ATS Analytics - Error while checking user browser!', err); } } @@ -265,20 +265,20 @@ function sendDataToAnalytic () { try { let dataToSend = {'Data': atsAnalyticsAdapter.context.events}; let strJSON = JSON.stringify(dataToSend); - utils.logInfo('ATS Analytics - tried to send analytics data!'); + logInfo('ATS Analytics - tried to send analytics data!'); ajax(analyticsUrl, function () { }, strJSON, {method: 'POST', contentType: 'application/json'}); } catch (err) { - utils.logError('ATS Analytics - request encounter an error: ', err); + logError('ATS Analytics - request encounter an error: ', err); } } // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { - utils.logInfo('ATS Analytics - preflight request!'); + logInfo('ATS Analytics - preflight request!'); ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { let samplingRateObject = JSON.parse(data); - utils.logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); + logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); let samplingRate = samplingRateObject['samplingRate']; setSamplingCookie(samplingRate); let samplingRateNumber = Number(samplingRate); @@ -332,7 +332,7 @@ let atsAnalyticsAdapter = Object.assign(adapter( } } } catch (err) { - utils.logError('ATS Analytics - preflight request encounter an error: ', err); + logError('ATS Analytics - preflight request encounter an error: ', err); } } } @@ -345,10 +345,10 @@ atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics; atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { if (samplingRate !== 0) { let shouldFireRequestValue = (Math.floor((Math.random() * 100 + 1)) === 100); - utils.logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); + logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); return shouldFireRequestValue; } else { - utils.logInfo('ATS Analytics - Should Fire Request: ', false); + logInfo('ATS Analytics - Should Fire Request: ', false); return false; } }; @@ -359,7 +359,7 @@ atsAnalyticsAdapter.getUserAgent = function () { // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { - utils.logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); + logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); return; } atsAnalyticsAdapter.context = { @@ -367,7 +367,7 @@ atsAnalyticsAdapter.enableAnalytics = function (config) { pid: config.options.pid }; let initOptions = config.options; - utils.logInfo('ATS Analytics - adapter enabled! '); + logInfo('ATS Analytics - adapter enabled! '); atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function }; diff --git a/modules/audiencerunBidAdapter.js b/modules/audiencerunBidAdapter.js index da0cbb39925..2c100bce27b 100644 --- a/modules/audiencerunBidAdapter.js +++ b/modules/audiencerunBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isFn, logError, getValue, getBidIdParameter, _each, isArray, triggerPixel } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -20,7 +20,7 @@ let requestedBids = []; function getPageUrl(bidderRequest) { return ( config.getConfig('pageUrl') || - utils.deepAccess(bidderRequest, 'refererInfo.referer') || + deepAccess(bidderRequest, 'refererInfo.referer') || null ); } @@ -32,8 +32,8 @@ function getPageUrl(bidderRequest) { * @returns {number} */ function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -61,8 +61,8 @@ export const spec = { */ isBidRequestValid: function (bid) { let isValid = true; - if (!utils.deepAccess(bid, 'params.zoneId')) { - utils.logError('AudienceRun zoneId parameter is required. Bid aborted.'); + if (!deepAccess(bid, 'params.zoneId')) { + logError('AudienceRun zoneId parameter is required. Bid aborted.'); isValid = false; } return isValid; @@ -77,19 +77,19 @@ export const spec = { */ buildRequests: function (bidRequests, bidderRequest) { const bids = bidRequests.map((bid) => { - const sizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes', []); + const sizes = deepAccess(bid, 'mediaTypes.banner.sizes', []); return { - zoneId: utils.getValue(bid.params, 'zoneId'), + zoneId: getValue(bid.params, 'zoneId'), sizes: sizes.map((size) => ({ w: size[0], h: size[1], })), bidfloor: getBidFloor(bid), bidId: bid.bidId, - bidderRequestId: utils.getBidIdParameter('bidderRequestId', bid), - adUnitCode: utils.getBidIdParameter('adUnitCode', bid), - auctionId: utils.getBidIdParameter('auctionId', bid), - transactionId: utils.getBidIdParameter('transactionId', bid), + bidderRequestId: getBidIdParameter('bidderRequestId', bid), + adUnitCode: getBidIdParameter('adUnitCode', bid), + auctionId: getBidIdParameter('auctionId', bid), + transactionId: getBidIdParameter('transactionId', bid), }; }); @@ -133,7 +133,7 @@ export const spec = { */ interpretResponse: function (serverResponse, bidRequest) { const bids = []; - utils._each(serverResponse.body.bid, function (bidObject) { + _each(serverResponse.body.bid, function (bidObject) { if (!bidObject.cpm || bidObject.cpm === null || !bidObject.adm) { return; } @@ -196,7 +196,7 @@ export const spec = { * @param {Array} timeoutData timeout specific data */ onTimeout: function (timeoutData) { - if (!utils.isArray(timeoutData)) { + if (!isArray(timeoutData)) { return; } @@ -204,7 +204,7 @@ export const spec = { const bidOnTimeout = requestedBids.find((requestedBid) => requestedBid.bidId === bid.bidId); if (bidOnTimeout) { - utils.triggerPixel( + triggerPixel( `${TIMEOUT_EVENT_URL}/${bidOnTimeout.zoneId}/${bidOnTimeout.bidId}` ); } diff --git a/modules/automatadBidAdapter.js b/modules/automatadBidAdapter.js index 415c52ba6d3..2cfcfbe98b4 100644 --- a/modules/automatadBidAdapter.js +++ b/modules/automatadBidAdapter.js @@ -1,5 +1,5 @@ +import { logInfo } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js' -import * as utils from '../src/utils.js' import {BANNER} from '../src/mediaTypes.js' import {ajax} from '../src/ajax.js' @@ -92,7 +92,7 @@ export const spec = { }) }) } else { - utils.logInfo('automatad :: no valid responses to interpret') + logInfo('automatad :: no valid responses to interpret') } return bidResponses diff --git a/modules/axonixBidAdapter.js b/modules/axonixBidAdapter.js index daaac27e6a4..7cd8f63bd2a 100644 --- a/modules/axonixBidAdapter.js +++ b/modules/axonixBidAdapter.js @@ -1,7 +1,7 @@ +import { isArray, logError, deepAccess, isEmpty, triggerPixel, replaceAuctionPrice } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { ajax } from '../src/ajax.js'; const BIDDER_CODE = 'axonix'; @@ -68,9 +68,9 @@ export const spec = { // video bid request validation if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('mimes') || - !utils.isArray(bid.mediaTypes[VIDEO].mimes) || + !isArray(bid.mediaTypes[VIDEO].mimes) || bid.mediaTypes[VIDEO].mimes.length === 0) { - utils.logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); + logError('mimes are mandatory for video bid request. Ad Unit: ', JSON.stringify(bid)); return false; } @@ -142,7 +142,7 @@ export const spec = { interpretResponse: function(serverResponse) { const response = serverResponse ? serverResponse.body : []; - if (!utils.isArray(response)) { + if (!isArray(response)) { return []; } @@ -160,9 +160,9 @@ export const spec = { }, onTimeout: function(timeoutData) { - const params = utils.deepAccess(timeoutData, '0.params.0'); + const params = deepAccess(timeoutData, '0.params.0'); - if (!utils.isEmpty(params)) { + if (!isEmpty(params)) { ajax(getURL(params, 'prebid/timeout'), null, timeoutData[0], { method: 'POST', options: { @@ -177,7 +177,7 @@ export const spec = { const { nurl } = bid || {}; if (bid.nurl) { - utils.triggerPixel(utils.replaceAuctionPrice(nurl, bid.cpm)); + triggerPixel(replaceAuctionPrice(nurl, bid.cpm)); }; } } diff --git a/modules/beachfrontBidAdapter.js b/modules/beachfrontBidAdapter.js index 3531fa45d1b..a882a796851 100644 --- a/modules/beachfrontBidAdapter.js +++ b/modules/beachfrontBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, deepAccess, isArray, parseSizesInput, isFn, parseUrl, getUniqueIdentifierStr } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; @@ -34,21 +34,21 @@ export const spec = { isBidRequestValid(bid) { if (isVideoBid(bid)) { if (!getVideoBidParam(bid, 'appId')) { - utils.logWarn('Beachfront: appId param is required for video bids.'); + logWarn('Beachfront: appId param is required for video bids.'); return false; } if (!getVideoBidParam(bid, 'bidfloor')) { - utils.logWarn('Beachfront: bidfloor param is required for video bids.'); + logWarn('Beachfront: bidfloor param is required for video bids.'); return false; } } if (isBannerBid(bid)) { if (!getBannerBidParam(bid, 'appId')) { - utils.logWarn('Beachfront: appId param is required for banner bids.'); + logWarn('Beachfront: appId param is required for banner bids.'); return false; } if (!getBannerBidParam(bid, 'bidfloor')) { - utils.logWarn('Beachfront: bidfloor param is required for banner bids.'); + logWarn('Beachfront: bidfloor param is required for banner bids.'); return false; } } @@ -85,12 +85,12 @@ export const spec = { if (isVideoBid(bidRequest)) { if (!response || !response.bidPrice) { - utils.logWarn(`No valid video bids from ${spec.code} bidder`); + logWarn(`No valid video bids from ${spec.code} bidder`); return []; } let sizes = getVideoSizes(bidRequest); let firstSize = getFirstSize(sizes); - let context = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + let context = deepAccess(bidRequest, 'mediaTypes.video.context'); let responseType = getVideoBidParam(bidRequest, 'responseType') || 'both'; let responseMeta = Object.assign({ mediaType: VIDEO, advertiserDomains: [] }, response.meta); let bidResponse = { @@ -119,7 +119,7 @@ export const spec = { return bidResponse; } else { if (!response || !response.length) { - utils.logWarn(`No valid banner bids from ${spec.code} bidder`); + logWarn(`No valid banner bids from ${spec.code} bidder`); return []; } return response @@ -148,7 +148,7 @@ export const spec = { getUserSyncs(syncOptions, serverResponses = [], gdprConsent = {}, uspConsent = '') { let syncs = []; let { gdprApplies, consentString = '' } = gdprConsent; - let bannerResponse = find(serverResponses, (res) => utils.isArray(res.body)); + let bannerResponse = find(serverResponses, (res) => isArray(res.body)); if (bannerResponse) { if (syncOptions.iframeEnabled) { @@ -206,7 +206,7 @@ function getFirstSize(sizes) { } function parseSizes(sizes) { - return utils.parseSizesInput(sizes).map(size => { + return parseSizesInput(sizes).map(size => { let [ width, height ] = size.split('x'); return { w: parseInt(width, 10) || undefined, @@ -216,11 +216,11 @@ function parseSizes(sizes) { } function getVideoSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } function getBannerSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } function getOsVersion() { @@ -257,33 +257,33 @@ function getDoNotTrack() { } function isVideoBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.video'); + return deepAccess(bid, 'mediaTypes.video'); } function isBannerBid(bid) { - return utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); + return deepAccess(bid, 'mediaTypes.banner') || !isVideoBid(bid); } function getVideoBidParam(bid, key) { - return utils.deepAccess(bid, 'params.video.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.video.' + key) || deepAccess(bid, 'params.' + key); } function getBannerBidParam(bid, key) { - return utils.deepAccess(bid, 'params.banner.' + key) || utils.deepAccess(bid, 'params.' + key); + return deepAccess(bid, 'params.banner.' + key) || deepAccess(bid, 'params.' + key); } function getPlayerBidParam(bid, key, defaultValue) { - let param = utils.deepAccess(bid, 'params.player.' + key); + let param = deepAccess(bid, 'params.player.' + key); return param === undefined ? defaultValue : param; } function getBannerBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'banner', size: '*' }) : {}; return floorInfo.floor || getBannerBidParam(bid, 'bidfloor'); } function getVideoBidFloor(bid) { - let floorInfo = utils.isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; + let floorInfo = isFn(bid.getFloor) ? bid.getFloor({ currency: CURRENCY, mediaType: 'video', size: '*' }) : {}; return floorInfo.floor || getVideoBidParam(bid, 'bidfloor'); } @@ -297,7 +297,7 @@ function isBannerBidValid(bid) { function getTopWindowLocation(bidderRequest) { let url = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer; - return utils.parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); + return parseUrl(config.getConfig('pageUrl') || url, { decodeSearchAsString: true }); } function getTopWindowReferrer() { @@ -316,7 +316,7 @@ function getEids(bid) { function getUserId(bid) { return ({ key, source, rtiPartner, atype }) => { - let id = utils.deepAccess(bid, `userId.${key}`); + let id = deepAccess(bid, `userId.${key}`); return id ? formatEid(id, source, rtiPartner, atype) : null; }; } @@ -364,7 +364,7 @@ function createVideoRequestData(bid, bidderRequest) { isPrebid: true, appId: appId, domain: document.location.hostname, - id: utils.getUniqueIdentifierStr(), + id: getUniqueIdentifierStr(), imp: [{ video: Object.assign({ w: firstSize.w, @@ -469,7 +469,7 @@ function createBannerRequestData(bids, bidderRequest) { } SUPPORTED_USER_IDS.forEach(({ key, queryParam }) => { - let id = utils.deepAccess(bids, `0.userId.${key}`) + let id = deepAccess(bids, `0.userId.${key}`) if (id) { payload[queryParam] = id; } diff --git a/modules/beopBidAdapter.js b/modules/beopBidAdapter.js index aed5d04a151..a6bc8a5687d 100644 --- a/modules/beopBidAdapter.js +++ b/modules/beopBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isArray, logWarn, triggerPixel, buildUrl, logInfo, getValue, getBidIdParameter } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'beop'; @@ -36,7 +36,7 @@ export const spec = { */ buildRequests: function(validBidRequests, bidderRequest) { const slots = validBidRequests.map(beOpRequestSlotsMaker); - let pageUrl = utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); + let pageUrl = deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || deepAccess(window, 'location.href'); let fpd = config.getLegacyFpd(config.getConfig('ortb2')); let gdpr = bidderRequest.gdprConsent; let firstSlot = slots[0]; @@ -50,7 +50,7 @@ export const spec = { kwds: (fpd && fpd.site && fpd.site.keywords) || [], dbg: false, slts: slots, - is_amp: utils.deepAccess(bidderRequest, 'referrerInfo.isAmp'), + is_amp: deepAccess(bidderRequest, 'referrerInfo.isAmp'), tc_string: (gdpr && gdpr.gdprApplies) ? gdpr.consentString : null, }; const payloadString = JSON.stringify(payloadObject); @@ -61,7 +61,7 @@ export const spec = { } }, interpretResponse: function(serverResponse, request) { - if (serverResponse && serverResponse.body && utils.isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { + if (serverResponse && serverResponse.body && isArray(serverResponse.body.bids) && serverResponse.body.bids.length > 0) { return serverResponse.body.bids; } return []; @@ -73,8 +73,8 @@ export const spec = { let trackingParams = buildTrackingParams(timeoutData, 'timeout', timeoutData.timeout); - utils.logWarn(BIDDER_CODE + ': timed out request'); - utils.triggerPixel(utils.buildUrl({ + logWarn(BIDDER_CODE + ': timed out request'); + triggerPixel(buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -87,8 +87,8 @@ export const spec = { } let trackingParams = buildTrackingParams(bid, 'won', bid.cpm); - utils.logInfo(BIDDER_CODE + ': won request'); - utils.triggerPixel(utils.buildUrl({ + logInfo(BIDDER_CODE + ': won request'); + triggerPixel(buildUrl({ protocol: 'https', hostname: 't.beop.io', pathname: '/bid', @@ -113,8 +113,8 @@ function buildTrackingParams(data, info, value) { } function beOpRequestSlotsMaker(bid) { - const bannerSizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); - const publisherCurrency = config.getConfig('currency.adServerCurrency') || utils.getValue(bid.params, 'currency') || 'EUR'; + const bannerSizes = deepAccess(bid, 'mediaTypes.banner.sizes'); + const publisherCurrency = config.getConfig('currency.adServerCurrency') || getValue(bid.params, 'currency') || 'EUR'; let floor; if (typeof bid.getFloor === 'function') { const floorInfo = bid.getFloor({currency: publisherCurrency, mediaType: 'banner', size: [1, 1]}); @@ -123,19 +123,19 @@ function beOpRequestSlotsMaker(bid) { } } return { - sizes: utils.isArray(bannerSizes) ? bannerSizes : bid.sizes, + sizes: isArray(bannerSizes) ? bannerSizes : bid.sizes, flr: floor, - pid: utils.getValue(bid.params, 'accountId'), - nid: utils.getValue(bid.params, 'networkId'), - nptnid: utils.getValue(bid.params, 'networkPartnerId'), - bid: utils.getBidIdParameter('bidId', bid), - brid: utils.getBidIdParameter('bidderRequestId', bid), - name: utils.getBidIdParameter('adUnitCode', bid), - aid: utils.getBidIdParameter('auctionId', bid), - tid: utils.getBidIdParameter('transactionId', bid), - brc: utils.getBidIdParameter('bidRequestsCount', bid), - bdrc: utils.getBidIdParameter('bidderRequestCount', bid), - bwc: utils.getBidIdParameter('bidderWinsCount', bid), + pid: getValue(bid.params, 'accountId'), + nid: getValue(bid.params, 'networkId'), + nptnid: getValue(bid.params, 'networkPartnerId'), + bid: getBidIdParameter('bidId', bid), + brid: getBidIdParameter('bidderRequestId', bid), + name: getBidIdParameter('adUnitCode', bid), + aid: getBidIdParameter('auctionId', bid), + tid: getBidIdParameter('transactionId', bid), + brc: getBidIdParameter('bidRequestsCount', bid), + bdrc: getBidIdParameter('bidderRequestCount', bid), + bwc: getBidIdParameter('bidderWinsCount', bid), } } diff --git a/modules/bidViewabilityIO.js b/modules/bidViewabilityIO.js index 4651e424d00..d936fb4aeec 100644 --- a/modules/bidViewabilityIO.js +++ b/modules/bidViewabilityIO.js @@ -1,7 +1,7 @@ +import { logMessage } from '../src/utils.js'; import { config } from '../src/config.js'; import * as events from '../src/events.js'; import { EVENTS } from '../src/constants.json'; -import * as utils from '../src/utils.js'; const MODULE_NAME = 'bidViewabilityIO'; const CONFIG_ENABLED = 'enabled'; @@ -23,8 +23,8 @@ export let isSupportedMediaType = (bid) => { return supportedMediaTypes.indexOf(bid.mediaType) > -1; } -let logMessage = (message) => { - return utils.logMessage(`${MODULE_NAME}: ${message}`); +let _logMessage = (message) => { + return logMessage(`${MODULE_NAME}: ${message}`); } // returns options for the iO that detects if the ad is viewable @@ -43,7 +43,7 @@ export let markViewed = (bid, entry, observer) => { return () => { observer.unobserve(entry.target); events.emit(EVENTS.BID_VIEWABLE, bid); - logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); + _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} was viewed`); } } @@ -59,13 +59,13 @@ export let viewCallbackFactory = (bid) => { return (entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { - logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + _logMessage(`viewable timer starting for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); entry.target.view_tracker = setTimeout(markViewed(bid, entry, observer), IAB_VIEWABLE_DISPLAY_TIME); } else { - logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); + _logMessage(`id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode} is out of view`); if (entry.target.view_tracker) { clearTimeout(entry.target.view_tracker); - logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); + _logMessage(`viewable timer stopped for id: ${entry.target.getAttribute('id')} code: ${bid.adUnitCode}`); } } }); diff --git a/modules/bidglassBidAdapter.js b/modules/bidglassBidAdapter.js index b77ca474e13..3184372881b 100644 --- a/modules/bidglassBidAdapter.js +++ b/modules/bidglassBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { _each, isArray, getBidIdParameter, deepClone, getUniqueIdentifierStr } from '../src/utils.js'; // import {config} from 'src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; @@ -69,12 +69,12 @@ export const spec = { let bidglass = window['bidglass']; - utils._each(validBidRequests, function(bid) { - bid.sizes = ((utils.isArray(bid.sizes) && utils.isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); - bid.sizes = bid.sizes.filter(size => utils.isArray(size)); + _each(validBidRequests, function(bid) { + bid.sizes = ((isArray(bid.sizes) && isArray(bid.sizes[0])) ? bid.sizes : [bid.sizes]); + bid.sizes = bid.sizes.filter(size => isArray(size)); - var adUnitId = utils.getBidIdParameter('adUnitId', bid.params); - var options = utils.deepClone(bid.params); + var adUnitId = getBidIdParameter('adUnitId', bid.params); + var options = deepClone(bid.params); delete options.adUnitId; @@ -96,7 +96,7 @@ export const spec = { // Stuff to send: page URL const bidReq = { - reqId: utils.getUniqueIdentifierStr(), + reqId: getUniqueIdentifierStr(), imps: imps, ref: getReferer(), ori: getOrigins() @@ -125,7 +125,7 @@ export const spec = { interpretResponse: function(serverResponse) { const bidResponses = []; - utils._each(serverResponse.body.bidResponses, function(serverBid) { + _each(serverResponse.body.bidResponses, function(serverBid) { const bidResponse = { requestId: serverBid.requestId, cpm: parseFloat(serverBid.cpm), diff --git a/modules/bidscubeBidAdapter.js b/modules/bidscubeBidAdapter.js index d3f27a5ac6d..951bd97d255 100644 --- a/modules/bidscubeBidAdapter.js +++ b/modules/bidscubeBidAdapter.js @@ -1,6 +1,6 @@ +import { logMessage, getWindowLocation } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js' -import * as utils from '../src/utils.js' const BIDDER_CODE = 'bidscube' const URL = 'https://supply.bidscube.com/?c=o&m=multi' @@ -20,9 +20,9 @@ export const spec = { try { window.top.location.toString() winTop = window.top - } catch (e) { utils.logMessage(e) } + } catch (e) { logMessage(e) } - const location = utils.getWindowLocation() + const location = getWindowLocation() const placements = [] for (let i = 0; i < validBidRequests.length; i++) { diff --git a/modules/bizzclickBidAdapter.js b/modules/bizzclickBidAdapter.js index 95c53b78de2..38195f8f9d9 100644 --- a/modules/bizzclickBidAdapter.js +++ b/modules/bizzclickBidAdapter.js @@ -1,6 +1,6 @@ +import { logMessage, getDNT, deepSetValue, deepAccess, _map, logWarn } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import {config} from '../src/config.js'; const BIDDER_CODE = 'bizzclick'; const ACCOUNTID_MACROS = '[account_id]'; @@ -67,7 +67,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; let bids = []; for (let bidRequest of validBidRequests) { @@ -80,7 +80,7 @@ export const spec = { device: { w: winTop.screen.width, h: winTop.screen.height, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '', }, site: { @@ -124,12 +124,12 @@ export const spec = { } if (bidRequest) { if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) { - utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); - utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); + deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0); + deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString); } if (bidRequest.uspConsent !== undefined) { - utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); + deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent); } } bids.push(data) @@ -194,7 +194,7 @@ export const spec = { * @returns {boolean} */ const checkRequestType = (bidRequest, type) => { - return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); + return (typeof deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined'); } const parseNative = admObject => { const { assets, link, imptrackers, jstracker } = admObject.native; @@ -240,7 +240,7 @@ const addNativeParameters = bidRequest => { id: bidRequest.transactionId, ver: NATIVE_VERSION, }; - const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => { + const assets = _map(bidRequest.mediaTypes.native, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, @@ -286,7 +286,7 @@ const parseSizes = (bid, mediaType) => { mediaTypes.video.w, mediaTypes.video.h ]; - } else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { + } else if (Array.isArray(deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) { size = bid.mediaTypes.video.playerSize[0]; } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) { size = bid.sizes[0]; @@ -299,7 +299,7 @@ const parseSizes = (bid, mediaType) => { } else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) { sizes = bid.sizes } else { - utils.logWarn('no sizes are setup or found'); + logWarn('no sizes are setup or found'); } return sizes } From b4ea663a1cdfbd8bf0eda227879a5e38aa990d34 Mon Sep 17 00:00:00 2001 From: TheMediaGrid <44166371+TheMediaGrid@users.noreply.github.com> Date: Tue, 28 Sep 2021 17:57:22 +0300 Subject: [PATCH 23/84] TheMediaGrid: fix bug with wrong vastUrl (#7507) * Added TheMediaGridNM Bid Adapter * Updated required params for TheMediaGridNM Bid Adapter * Update TheMediGridNM Bid Adapter * Fix tests for TheMediaGridNM Bid Adapter * Fixes after review for TheMediaGridNM Bid Adapter * Add support of multi-format in TheMediaGrid Bid Adapter * Update sync url for grid and gridNM Bid Adapters * TheMediaGrid Bid Adapter: added keywords adUnit parameter * Update TheMediaGrid Bid Adapter to support keywords from config * Implement new request format for TheMediaGrid Bid Adapter * Fix jwpseg params for TheMediaGrid Bid Adapter * Update unit tests for The Media Grid Bid Adapter * Fix typo in TheMediaGrid Bid Adapter * Added test for jwTargeting in TheMediaGrid Bid Adapter * The new request format was made by default in TheMediaGrid Bid Adapter * Update userId format in ad request for TheMediaGrid Bid Adapter * Added bidFloor parameter for TheMediaGrid Bid Adapter * Fix for review TheMediaGrid Bid Adapter * Support floorModule in TheMediaGrid Bid Adapter * Fix empty bidfloor for TheMediaGrid Bid Adapter * Some change to restart autotests * Fix userIds format for TheMediaGrid Bid Adapter * Remove digitrust userId from TheMediaGrid Bid Adapter * Protocols was added in video section in ad request for TheMediaGrid Bid Adapter * TheMediaGrid: fix trouble with alias using * TheMediaGridNM: fix trouble with alias * TheMediaGrid Bid Adapter: added support of PBAdSlot module * TheMediaGrid Bid Adapter: fix typo * GridNM Bid Adapter: use absent in params data from mediaTypes * GridNM Bid Adapter: fix md file + add advertiserDomains support * TheMediaGrid and gridNM Bid Adapter: minor netRevenue fixes * gridNM Bid Adapter updates after review * TheMediaGrid Bid Adapter: fix keywords workflow * fix testing and kick off lgtm again * TheMediaGrid: added ext.bidder.grid.demandSource processing * TheMediaGrid: added user.id from fpd cookie * TheMediaGrid: control cookie setting via bidder config * TheMediaGrid: use localStorage instead cookie * TheMediaGridNM Bid Adapter: update adapter to use /hbjson endpoint * TheMediaGridNM: fix unnecessary conditions * TheMediaGrid: fix bug with nurl field in response * TheMediaGrid: update test Co-authored-by: Chris Huie --- modules/gridBidAdapter.js | 3 +- test/spec/modules/gridBidAdapter_spec.js | 40 ++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/modules/gridBidAdapter.js b/modules/gridBidAdapter.js index 9411f38ebd8..aba840793d4 100644 --- a/modules/gridBidAdapter.js +++ b/modules/gridBidAdapter.js @@ -382,8 +382,7 @@ function _addBidResponse(serverBid, bidRequest, bidResponses) { bidResponse.adResponse = { content: bidResponse.vastXml }; - } - if (serverBid.nurl) { + } else if (serverBid.nurl) { bidResponse.vastUrl = serverBid.nurl; } bidResponse.mediaType = VIDEO; diff --git a/test/spec/modules/gridBidAdapter_spec.js b/test/spec/modules/gridBidAdapter_spec.js index 7913dd7b44d..f31b8f16ef7 100644 --- a/test/spec/modules/gridBidAdapter_spec.js +++ b/test/spec/modules/gridBidAdapter_spec.js @@ -874,6 +874,22 @@ describe('TheMediaGrid Adapter', function () { }, 'adUnitCode': 'adunit-code-2', 'sizes': [[300, 250], [300, 600]], + 'bidId': '112432ab4f34', + 'bidderRequestId': '5f2009617a7c0a', + 'auctionId': '1cbd2feafe5e8b', + 'mediaTypes': { + 'video': { + 'context': 'instream' + } + } + }, + { + 'bidder': 'grid', + 'params': { + 'uid': '15' + }, + 'adUnitCode': 'adunit-code-2', + 'sizes': [[300, 250], [300, 600]], 'bidId': 'a74b342f8cd', 'bidderRequestId': '5f2009617a7c0a', 'auctionId': '1cbd2feafe5e8b', @@ -888,7 +904,8 @@ describe('TheMediaGrid Adapter', function () { {'bid': [{'impid': '659423fff799cb', 'price': 1.15, 'adm': '\n<\/Ad>\n<\/VAST>', 'auid': 11, content_type: 'video', w: 300, h: 600}], 'seat': '2'}, {'bid': [{'impid': '2bc598e42b6a', 'price': 1.00, 'adm': '\n<\/Ad>\n<\/VAST>', 'auid': 12, content_type: 'video'}], 'seat': '2'}, {'bid': [{'impid': '23312a43bc42', 'price': 2.00, 'nurl': 'https://some_test_vast_url.com', 'auid': 13, content_type: 'video', 'adomain': ['example.com'], w: 300, h: 600}], 'seat': '2'}, - {'bid': [{'impid': 'a74b342f8cd', 'price': 1.50, 'nurl': '', 'auid': 14, content_type: 'video'}], 'seat': '2'} + {'bid': [{'impid': '112432ab4f34', 'price': 1.80, 'adm': '\n<\/Ad>\n<\/VAST>', 'nurl': 'https://wrong_url.com', 'auid': 14, content_type: 'video', 'adomain': ['example.com'], w: 300, h: 600}], 'seat': '2'}, + {'bid': [{'impid': 'a74b342f8cd', 'price': 1.50, 'nurl': '', 'auid': 15, content_type: 'video'}], 'seat': '2'} ]; const request = spec.buildRequests(bidRequests); const expectedResponse = [ @@ -945,7 +962,26 @@ describe('TheMediaGrid Adapter', function () { advertiserDomains: ['example.com'] }, 'vastUrl': 'https://some_test_vast_url.com', - } + }, + { + 'requestId': '112432ab4f34', + 'cpm': 1.80, + 'creativeId': 14, + 'dealId': undefined, + 'width': 300, + 'height': 600, + 'currency': 'USD', + 'mediaType': 'video', + 'netRevenue': true, + 'ttl': 360, + 'meta': { + advertiserDomains: ['example.com'] + }, + 'vastXml': '\n<\/Ad>\n<\/VAST>', + 'adResponse': { + 'content': '\n<\/Ad>\n<\/VAST>' + } + }, ]; const result = spec.interpretResponse({'body': {'seatbid': response}}, request); From eb8c4cb661541f7c36146eb61d4e6aaa729cf011 Mon Sep 17 00:00:00 2001 From: Lisa Benmore Date: Tue, 28 Sep 2021 08:47:45 -0700 Subject: [PATCH 24/84] Gumgum: ADTS-156 Improve GPID support by checking for value in new location within request object (#7500) --- modules/gumgumBidAdapter.js | 6 ++++-- test/spec/modules/gumgumBidAdapter_spec.js | 10 +++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/modules/gumgumBidAdapter.js b/modules/gumgumBidAdapter.js index 7ac43d32d56..0580675eed8 100644 --- a/modules/gumgumBidAdapter.js +++ b/modules/gumgumBidAdapter.js @@ -298,8 +298,10 @@ function buildRequests(validBidRequests, bidderRequest) { // ADTS-134 Retrieve ID envelopes for (const eid in eids) data[eid] = eids[eid]; - // ADJS-1024 - if (utils.deepAccess(ortb2Imp, 'ext.data.adserver.name')) { + // ADJS-1024 & ADSS-1297 + if (utils.deepAccess(ortb2Imp, 'ext.data.pbadslot')) { + gpid = utils.deepAccess(ortb2Imp, 'ext.data.pbadslot') + } else if (utils.deepAccess(ortb2Imp, 'ext.data.adserver.name')) { gpid = ortb2Imp.ext.data.adserver.adslot } diff --git a/test/spec/modules/gumgumBidAdapter_spec.js b/test/spec/modules/gumgumBidAdapter_spec.js index e91308849ed..e11123729e0 100644 --- a/test/spec/modules/gumgumBidAdapter_spec.js +++ b/test/spec/modules/gumgumBidAdapter_spec.js @@ -229,13 +229,21 @@ describe('gumgumAdapter', function () { expect(bidRequest.data).to.not.have.property('irisid'); }); - it('should set the global placement id (gpid)', function () { + it('should set the global placement id (gpid) if in adserver property', function () { const req = { ...bidRequests[0], ortb2Imp: { ext: { data: { adserver: { name: 'test', adslot: 123456 } } } } } const bidRequest = spec.buildRequests([req])[0]; expect(bidRequest.data).to.have.property('gpid'); expect(bidRequest.data.gpid).to.equal(123456); }); + it('should set the global placement id (gpid) if in pbadslot property', function () { + const pbadslot = 'abc123' + const req = { ...bidRequests[0], ortb2Imp: { ext: { data: { pbadslot } } } } + const bidRequest = spec.buildRequests([req])[0]; + expect(bidRequest.data).to.have.property('gpid'); + expect(bidRequest.data.gpid).to.equal(pbadslot); + }); + it('should set the bid floor if getFloor module is not present but static bid floor is defined', function () { const req = { ...bidRequests[0], params: { bidfloor: 42 } } const bidRequest = spec.buildRequests([req])[0]; From 35b1d71b986da92821d3d17ffe0c874a43daa5a6 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 09:49:37 -0700 Subject: [PATCH 25/84] PBjs Core : User sync iframe over image (#7454) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * Issue 7330 first loops through iframe syncs (it used to do pixel syncs first) If a bidder gets an iframe, mark it. Then PBJS should loop through pixel syncs If a bidder is about to get a pixel but already got an iframe sync, skip it. --- src/userSync.js | 14 ++++++++++++-- test/spec/userSync_spec.js | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/userSync.js b/src/userSync.js index f653880fa29..fc9f577fd7e 100644 --- a/src/userSync.js +++ b/src/userSync.js @@ -91,10 +91,10 @@ export function newUserSync(userSyncDependencies) { } try { - // Image pixels - fireImagePixels(); // Iframe syncs loadIframes(); + // Image pixels + fireImagePixels(); } catch (e) { return utils.logError('Error firing user syncs', e); } @@ -138,11 +138,21 @@ export function newUserSync(userSyncDependencies) { if (!(permittedPixels.iframe)) { return; } + forEachFire(queue.iframe, (sync) => { let [bidderName, iframeUrl] = sync; utils.logMessage(`Invoking iframe user sync for bidder: ${bidderName}`); // Insert iframe into DOM utils.insertUserSyncIframe(iframeUrl); + // for a bidder, if iframe sync is present then remove image pixel + removeImagePixelsForBidder(queue, bidderName); + }); + } + + function removeImagePixelsForBidder(queue, iframeSyncBidderName) { + queue.image = queue.image.filter(imageSync => { + let imageSyncBidderName = imageSync[0]; + return imageSyncBidderName !== iframeSyncBidderName }); } diff --git a/test/spec/userSync_spec.js b/test/spec/userSync_spec.js index 55b613ce929..910ffe7b2d6 100644 --- a/test/spec/userSync_spec.js +++ b/test/spec/userSync_spec.js @@ -401,6 +401,33 @@ describe('user sync', function () { expect(insertUserSyncIframeStub.getCall(0).args[0]).to.equal('http://example.com/iframe'); }); + it('should not fire image pixel for a bidder if iframe pixel is fired for same bidder', function() { + const userSync = newUserSync({ + config: config.getConfig('userSync'), + browserSupportsCookies: true + }); + + config.setConfig({ + userSync: { + filterSettings: { + iframe: { + bidders: ['bidderXYZ'], + filter: 'include' + } + } + } + }); + // we are registering iframe and image sync for bidderXYZ and we expect image sync not to execute. + userSync.registerSync('image', 'testBidder', 'http://testBidder.example.com/image'); + userSync.registerSync('iframe', 'bidderXYZ', 'http://bidderXYZ.example.com/iframe'); + userSync.registerSync('image', 'bidderXYZ', 'http://bidderXYZ.example.com/image'); + userSync.syncUsers(); + expect(triggerPixelStub.getCall(0)).to.not.be.null; + expect(triggerPixelStub.getCall(0).args[0]).to.exist.and.to.equal('http://testBidder.example.com/image'); + expect(triggerPixelStub.callCount).to.equal(1); // should not be 2 for 2 registered image syncs + expect(insertUserSyncIframeStub.getCall(0).args[0]).to.equal('http://bidderXYZ.example.com/iframe'); + }); + it('should override default image syncs if setConfig used image filter', function () { const userSync = newUserSync({ config: config.getConfig('userSync'), @@ -448,8 +475,9 @@ describe('user sync', function () { userSync.registerSync('iframe', 'testBidder', 'http://example.com/iframe'); userSync.registerSync('iframe', 'bidderXYZ', 'http://example.com/iframe-blocked'); userSync.syncUsers(); - expect(triggerPixelStub.getCall(0)).to.not.be.null; - expect(triggerPixelStub.getCall(0).args[0]).to.exist.and.to.equal('http://example.com'); + // expect(triggerPixelStub.getCall(0)).to.not.be.null; + expect(triggerPixelStub.getCall(0)).to.be.null;// image sync will not execute as iframe sync has executed for same bidder + // expect(triggerPixelStub.getCall(0).args[0]).to.exist.and.to.equal('http://example.com'); expect(triggerPixelStub.getCall(1)).to.be.null; expect(insertUserSyncIframeStub.getCall(0).args[0]).to.equal('http://example.com/iframe'); expect(insertUserSyncIframeStub.getCall(1)).to.be.null; From a5141af2f738be6980f19843315e5953da501ad7 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 10:46:58 -0700 Subject: [PATCH 26/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7493) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/proxistoreBidAdapter.js | 6 +- modules/pubCommonId.js | 22 ++-- modules/pubProvidedIdSystem.js | 6 +- modules/publinkIdSystem.js | 10 +- modules/pubmaticAnalyticsAdapter.js | 32 ++--- modules/pubmaticBidAdapter.js | 174 ++++++++++++++-------------- modules/pubperfAnalyticsAdapter.js | 6 +- modules/pubwiseAnalyticsAdapter.js | 12 +- modules/pubwiseBidAdapter.js | 46 ++++---- modules/pubxBidAdapter.js | 4 +- modules/pubxaiAnalyticsAdapter.js | 14 +-- modules/pulsepointBidAdapter.js | 26 ++--- modules/pxyzBidAdapter.js | 14 +-- modules/quantcastBidAdapter.js | 32 ++--- modules/radsBidAdapter.js | 10 +- 15 files changed, 207 insertions(+), 207 deletions(-) diff --git a/modules/proxistoreBidAdapter.js b/modules/proxistoreBidAdapter.js index 8b191c70e75..68151f820dd 100644 --- a/modules/proxistoreBidAdapter.js +++ b/modules/proxistoreBidAdapter.js @@ -1,5 +1,5 @@ +import { isFn, isPlainObject } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'proxistore'; const PROXISTORE_VENDOR_ID = 418; @@ -170,7 +170,7 @@ function interpretResponse(serverResponse, bidRequest) { } function _assignFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { // eslint-disable-next-line no-console console.log(bid.params.bidFloor); return bid.params.bidFloor ? bid.params.bidFloor : null; @@ -182,7 +182,7 @@ function _assignFloor(bid) { }); if ( - utils.isPlainObject(floor) && + isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'EUR' ) { diff --git a/modules/pubCommonId.js b/modules/pubCommonId.js index 427f775c44b..6ecf0723aae 100644 --- a/modules/pubCommonId.js +++ b/modules/pubCommonId.js @@ -3,7 +3,7 @@ * stored in the page's domain. When the module is included, an id is generated if needed, * persisted as a cookie, and automatically appended to all the bidRequest as bid.crumbs.pubcid. */ -import * as utils from '../src/utils.js'; +import { logMessage, parseUrl, buildUrl, triggerPixel, generateUUID, isArray } from '../src/utils.js'; import { config } from '../src/config.js'; import events from '../src/events.js'; import CONSTANTS from '../src/constants.json'; @@ -44,7 +44,7 @@ export function setStorageItem(key, val, expires) { storage.setDataInLocalStorage(key, val); } catch (e) { - utils.logMessage(e); + logMessage(e); } } @@ -74,7 +74,7 @@ export function getStorageItem(key) { } } } catch (e) { - utils.logMessage(e); + logMessage(e); } return val; @@ -89,7 +89,7 @@ export function removeStorageItem(key) { storage.removeDataFromLocalStorage(key + EXP_SUFFIX); storage.removeDataFromLocalStorage(key); } catch (e) { - utils.logMessage(e); + logMessage(e); } } @@ -141,13 +141,13 @@ function queuePixelCallback(pixelUrl, id) { id = id || ''; // Use pubcid as a cache buster - const urlInfo = utils.parseUrl(pixelUrl); + const urlInfo = parseUrl(pixelUrl); urlInfo.search.id = encodeURIComponent('pubcid:' + id); - const targetUrl = utils.buildUrl(urlInfo); + const targetUrl = buildUrl(urlInfo); events.on(CONSTANTS.EVENTS.AUCTION_END, function auctionEndHandler() { events.off(CONSTANTS.EVENTS.AUCTION_END, auctionEndHandler); - utils.triggerPixel(targetUrl); + triggerPixel(targetUrl); }); return true; @@ -177,7 +177,7 @@ export function requestBidHook(next, config) { if (typeof window[PUB_COMMON] === 'object') { // If the page includes its own pubcid object, then use that instead. pubcid = window[PUB_COMMON].getId(); - utils.logMessage(PUB_COMMON + ': pubcid = ' + pubcid); + logMessage(PUB_COMMON + ': pubcid = ' + pubcid); } else { // Otherwise get the existing cookie pubcid = readValue(ID_NAME); @@ -190,7 +190,7 @@ export function requestBidHook(next, config) { } // Generate a new id if (!pubcid) { - pubcid = utils.generateUUID(); + pubcid = generateUUID(); } // Update the cookie/storage with the latest expiration date writeValue(ID_NAME, pubcid, pubcidConfig.interval); @@ -205,14 +205,14 @@ export function requestBidHook(next, config) { } } - utils.logMessage('pbjs: pubcid = ' + pubcid); + logMessage('pbjs: pubcid = ' + pubcid); } // Append pubcid to each bid object, which will be incorporated // into bid requests later. if (adUnits && pubcid) { adUnits.forEach((unit) => { - if (unit.bids && utils.isArray(unit.bids)) { + if (unit.bids && isArray(unit.bids)) { unit.bids.forEach((bid) => { Object.assign(bid, {crumbs: {pubcid}}); }); diff --git a/modules/pubProvidedIdSystem.js b/modules/pubProvidedIdSystem.js index 0b2175f57cb..669d223c57f 100644 --- a/modules/pubProvidedIdSystem.js +++ b/modules/pubProvidedIdSystem.js @@ -6,7 +6,7 @@ */ import {submodule} from '../src/hook.js'; -import * as utils from '../src/utils.js'; +import { logInfo, isArray } from '../src/utils.js'; const MODULE_NAME = 'pubProvidedId'; @@ -27,7 +27,7 @@ export const pubProvidedIdSubmodule = { */ decode(value) { const res = value ? {pubProvidedId: value} : undefined; - utils.logInfo('PubProvidedId: Decoded value ' + JSON.stringify(res)); + logInfo('PubProvidedId: Decoded value ' + JSON.stringify(res)); return res; }, @@ -40,7 +40,7 @@ export const pubProvidedIdSubmodule = { getId(config) { const configParams = (config && config.params) || {}; let res = []; - if (utils.isArray(configParams.eids)) { + if (isArray(configParams.eids)) { res = res.concat(configParams.eids); } if (typeof configParams.eidsFunction === 'function') { diff --git a/modules/publinkIdSystem.js b/modules/publinkIdSystem.js index ca6ca9cf8d8..9acc741f7da 100644 --- a/modules/publinkIdSystem.js +++ b/modules/publinkIdSystem.js @@ -8,7 +8,7 @@ import {submodule} from '../src/hook.js'; import {getStorageManager} from '../src/storageManager.js'; import {ajax} from '../src/ajax.js'; -import * as utils from '../src/utils.js'; +import { parseUrl, buildUrl, logError } from '../src/utils.js'; import {uspDataHandler} from '../src/adapterManager.js'; const MODULE_NAME = 'publinkId'; @@ -23,7 +23,7 @@ function isHex(s) { } function publinkIdUrl(params, consentData) { - let url = utils.parseUrl('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink'); + let url = parseUrl('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink'); url.search = { deh: params.e, mpn: 'Prebid.js', @@ -39,7 +39,7 @@ function publinkIdUrl(params, consentData) { url.search.us_privacy = usPrivacyString; } - return utils.buildUrl(url); + return buildUrl(url); } function makeCallback(config = {}, consentData) { @@ -58,7 +58,7 @@ function makeCallback(config = {}, consentData) { if (isHex(config.params.e)) { ajax(publinkIdUrl(config.params, consentData), handleResponse, undefined, options); } else { - utils.logError('params.e must be a hex string'); + logError('params.e must be a hex string'); } } }; @@ -82,7 +82,7 @@ function getlocalValue() { return obj.publink; } } catch (e) { - utils.logError(e); + logError(e); } } } diff --git a/modules/pubmaticAnalyticsAdapter.js b/modules/pubmaticAnalyticsAdapter.js index 9aa40a2282d..2477ab4c0a3 100755 --- a/modules/pubmaticAnalyticsAdapter.js +++ b/modules/pubmaticAnalyticsAdapter.js @@ -1,9 +1,9 @@ +import { _each, pick, logWarn, isStr, isArray, logError } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; import { ajax } from '../src/ajax.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { getGlobal } from '../src/prebidGlobal.js'; /// /////////// CONSTANTS ////////////// @@ -69,7 +69,7 @@ function setMediaTypes(types, bid) { if (typeof types === 'object') { if (!bid.sizes) { bid.dimensions = []; - utils._each(types, (type) => + _each(types, (type) => bid.dimensions = bid.dimensions.concat( type.sizes.map(sizeToDimensions) ) @@ -81,13 +81,13 @@ function setMediaTypes(types, bid) { } function copyRequiredBidDetails(bid) { - return utils.pick(bid, [ + return pick(bid, [ 'bidder', 'bidId', 'status', () => NO_BID, // default a bid to NO_BID until response is recieved or bid is timed out 'finalSource as source', 'params', - 'adUnit', () => utils.pick(bid, [ + 'adUnit', () => pick(bid, [ 'adUnitCode', 'transactionId', 'sizes as dimensions', sizes => sizes.map(sizeToDimensions), @@ -115,7 +115,7 @@ function setBidStatus(bid, args) { } function parseBidResponse(bid) { - return utils.pick(bid, [ + return pick(bid, [ 'bidPriceUSD', () => { // todo: check whether currency cases are handled here if (typeof bid.currency === 'string' && bid.currency.toUpperCase() === CURRENCY_USD) { @@ -125,7 +125,7 @@ function parseBidResponse(bid) { if (typeof bid.getCpmInNewCurrency === 'function') { return window.parseFloat(Number(bid.getCpmInNewCurrency(CURRENCY_USD)).toFixed(BID_PRECISION)); } - utils.logWarn(LOG_PRE_FIX + 'Could not determine the Net cpm in USD for the bid thus using bid.cpm', bid); + logWarn(LOG_PRE_FIX + 'Could not determine the Net cpm in USD for the bid thus using bid.cpm', bid); return bid.cpm }, 'bidGrossCpmUSD', () => { @@ -136,7 +136,7 @@ function parseBidResponse(bid) { if (typeof getGlobal().convertCurrency === 'function') { return window.parseFloat(Number(getGlobal().convertCurrency(bid.originalCpm, bid.originalCurrency, CURRENCY_USD)).toFixed(BID_PRECISION)); } - utils.logWarn(LOG_PRE_FIX + 'Could not determine the Gross cpm in USD for the bid, thus using bid.originalCpm', bid); + logWarn(LOG_PRE_FIX + 'Could not determine the Gross cpm in USD for the bid, thus using bid.originalCpm', bid); return bid.originalCpm }, 'dealId', @@ -154,7 +154,7 @@ function parseBidResponse(bid) { 'mi', 'regexPattern', () => bid.regexPattern || undefined, 'partnerImpId', // partner impression ID - 'dimensions', () => utils.pick(bid, [ + 'dimensions', () => pick(bid, [ 'width', 'height' ]) @@ -171,7 +171,7 @@ function getDevicePlatform() { var deviceType = 3; try { var ua = navigator.userAgent; - if (ua && utils.isStr(ua) && ua.trim() != '') { + if (ua && isStr(ua) && ua.trim() != '') { ua = ua.toLowerCase().trim(); var isMobileRegExp = new RegExp('(mobi|tablet|ios).*'); if (ua.match(isMobileRegExp)) { @@ -325,9 +325,9 @@ function executeBidWonLoggerCall(auctionId, adUnitId) { function auctionInitHandler(args) { s2sBidders = (function() { let s2sConf = config.getConfig('s2sConfig'); - return (s2sConf && utils.isArray(s2sConf.bidders)) ? s2sConf.bidders : []; + return (s2sConf && isArray(s2sConf.bidders)) ? s2sConf.bidders : []; }()); - let cacheEntry = utils.pick(args, [ + let cacheEntry = pick(args, [ 'timestamp', 'timeout', 'bidderDonePendingCount', () => args.bidderRequests.length, @@ -353,7 +353,7 @@ function bidRequestedHandler(args) { function bidResponseHandler(args) { let bid = cache.auctions[args.auctionId].adUnitCodes[args.adUnitCode].bids[args.requestId]; if (!bid) { - utils.logError(LOG_PRE_FIX + 'Could not find associated bid request for bid response with requestId: ', args.requestId); + logError(LOG_PRE_FIX + 'Could not find associated bid request for bid response with requestId: ', args.requestId); return; } bid.source = formatSource(bid.source || args.source); @@ -404,7 +404,7 @@ function bidTimeoutHandler(args) { code: TIMEOUT_ERROR }; } else { - utils.logWarn(LOG_PRE_FIX + 'bid not found'); + logWarn(LOG_PRE_FIX + 'bid not found'); } }); } @@ -424,17 +424,17 @@ let pubmaticAdapter = Object.assign({}, baseAdapter, { profileId = Number(conf.options.profileId) || DEFAULT_PROFILE_ID; profileVersionId = Number(conf.options.profileVersionId) || DEFAULT_PROFILE_VERSION_ID; } else { - utils.logError(LOG_PRE_FIX + 'Config not found.'); + logError(LOG_PRE_FIX + 'Config not found.'); error = true; } if (!publisherId) { - utils.logError(LOG_PRE_FIX + 'Missing publisherId(Number).'); + logError(LOG_PRE_FIX + 'Missing publisherId(Number).'); error = true; } if (error) { - utils.logError(LOG_PRE_FIX + 'Not collecting data due to error(s).'); + logError(LOG_PRE_FIX + 'Not collecting data due to error(s).'); } else { baseAdapter.enableAnalytics.call(this, conf); } diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index 46e3257ae2e..fa1f04a25e2 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, _each, isBoolean, isStr, isArray, inIframe, mergeDeep, deepAccess, isNumber, deepSetValue, logInfo, logError, deepClone, convertTypes } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO, NATIVE } from '../src/mediaTypes.js'; import {config} from '../src/config.js'; @@ -124,7 +124,7 @@ const BB_RENDERER = { else if (bid.vastUrl) config.vastUrl = bid.vastUrl; if (!bid.vastXml && !bid.vastUrl) { - utils.logWarn(`${LOG_WARN_PREFIX}: No vastXml or vastUrl on bid, bailing...`); + logWarn(`${LOG_WARN_PREFIX}: No vastXml or vastUrl on bid, bailing...`); return; } @@ -142,7 +142,7 @@ const BB_RENDERER = { } if (renderer) renderer.bootstrap(config, ele); - else utils.logWarn(`${LOG_WARN_PREFIX}: Couldn't find a renderer with ${rendererId}`); + else logWarn(`${LOG_WARN_PREFIX}: Couldn't find a renderer with ${rendererId}`); }, newRenderer: function(rendererCode, adUnitCode) { var rendererUrl = RENDERER_URL.replace('$RENDERER', rendererCode); @@ -155,7 +155,7 @@ const BB_RENDERER = { try { renderer.setRender(BB_RENDERER.outstreamRender); } catch (err) { - utils.logWarn(`${LOG_WARN_PREFIX}: Error tying to setRender on renderer`, err); + logWarn(`${LOG_WARN_PREFIX}: Error tying to setRender on renderer`, err); } return renderer; @@ -180,9 +180,9 @@ let NATIVE_ASSET_ID_TO_KEY_MAP = {}; let NATIVE_ASSET_KEY_TO_ASSET_MAP = {}; // loading NATIVE_ASSET_ID_TO_KEY_MAP -utils._each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); +_each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); // loading NATIVE_ASSET_KEY_TO_ASSET_MAP -utils._each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); +_each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); function _getDomainFromURL(url) { let anchor = document.createElement('a'); @@ -191,8 +191,8 @@ function _getDomainFromURL(url) { } function _parseSlotParam(paramName, paramValue) { - if (!utils.isStr(paramValue)) { - paramValue && utils.logWarn(LOG_WARN_PREFIX + 'Ignoring param key: ' + paramName + ', expects string-value, found ' + typeof paramValue); + if (!isStr(paramValue)) { + paramValue && logWarn(LOG_WARN_PREFIX + 'Ignoring param key: ' + paramName + ', expects string-value, found ' + typeof paramValue); return UNDEFINED; } @@ -213,11 +213,11 @@ function _parseSlotParam(paramName, paramValue) { } function _cleanSlot(slotName) { - if (utils.isStr(slotName)) { + if (isStr(slotName)) { return slotName.replace(/^\s+/g, '').replace(/\s+$/g, ''); } if (slotName) { - utils.logWarn(BIDDER_CODE + ': adSlot must be a string. Ignoring adSlot'); + logWarn(BIDDER_CODE + ': adSlot must be a string. Ignoring adSlot'); } return ''; } @@ -243,7 +243,7 @@ function _parseAdSlot(bid) { // i.e size is specified in adslot, so consider that and ignore sizes array splits = splits[1].split('x'); if (splits.length != 2) { - utils.logWarn(LOG_WARN_PREFIX + 'AdSlot Error: adSlot not in required format'); + logWarn(LOG_WARN_PREFIX + 'AdSlot Error: adSlot not in required format'); return; } bid.params.width = parseInt(splits[0], 10); @@ -294,10 +294,10 @@ function _handleCustomParams(params, conf) { value = entry.f(value, conf); } - if (utils.isStr(value)) { + if (isStr(value)) { conf[key] = value; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Ignoring param : ' + key + ' with value : ' + CUSTOM_PARAMS[key] + ', expects string-value, found ' + typeof value); + logWarn(LOG_WARN_PREFIX + 'Ignoring param : ' + key + ' with value : ' + CUSTOM_PARAMS[key] + ', expects string-value, found ' + typeof value); } } } @@ -334,22 +334,22 @@ function _checkParamDataType(key, value, datatype) { var functionToExecute; switch (datatype) { case DATA_TYPES.BOOLEAN: - functionToExecute = utils.isBoolean; + functionToExecute = isBoolean; break; case DATA_TYPES.NUMBER: - functionToExecute = utils.isNumber; + functionToExecute = isNumber; break; case DATA_TYPES.STRING: - functionToExecute = utils.isStr; + functionToExecute = isStr; break; case DATA_TYPES.ARRAY: - functionToExecute = utils.isArray; + functionToExecute = isArray; break; } if (functionToExecute(value)) { return value; } - utils.logWarn(LOG_WARN_PREFIX + errMsg); + logWarn(LOG_WARN_PREFIX + errMsg); return UNDEFINED; } @@ -386,7 +386,7 @@ function _createNativeRequest(params) { } }; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Title Length is required for native ad: ' + JSON.stringify(params)); + logWarn(LOG_WARN_PREFIX + 'Error: Title Length is required for native ad: ' + JSON.stringify(params)); } break; case NATIVE_ASSETS.IMAGE.KEY: @@ -405,7 +405,7 @@ function _createNativeRequest(params) { } }; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Image sizes is required for native ad: ' + JSON.stringify(params)); + logWarn(LOG_WARN_PREFIX + 'Error: Image sizes is required for native ad: ' + JSON.stringify(params)); } break; case NATIVE_ASSETS.ICON.KEY: @@ -420,7 +420,7 @@ function _createNativeRequest(params) { } }; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Icon sizes is required for native ad: ' + JSON.stringify(params)); + logWarn(LOG_WARN_PREFIX + 'Error: Icon sizes is required for native ad: ' + JSON.stringify(params)); }; break; case NATIVE_ASSETS.VIDEO.KEY: @@ -500,13 +500,13 @@ function _createBannerRequest(bid) { var sizes = bid.mediaTypes.banner.sizes; var format = []; var bannerObj; - if (sizes !== UNDEFINED && utils.isArray(sizes)) { + if (sizes !== UNDEFINED && isArray(sizes)) { bannerObj = {}; if (!bid.params.width && !bid.params.height) { if (sizes.length === 0) { // i.e. since bid.params does not have width or height, and length of sizes is 0, need to ignore this banner imp bannerObj = UNDEFINED; - utils.logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); return bannerObj; } else { bannerObj.w = parseInt(sizes[0][0], 10); @@ -529,16 +529,16 @@ function _createBannerRequest(bid) { } } bannerObj.pos = 0; - bannerObj.topframe = utils.inIframe() ? 0 : 1; + bannerObj.topframe = inIframe() ? 0 : 1; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); bannerObj = UNDEFINED; } return bannerObj; } function _createVideoRequest(bid) { - var videoData = utils.mergeDeep(utils.deepAccess(bid.mediaTypes, 'video'), bid.params.video); + var videoData = mergeDeep(deepAccess(bid.mediaTypes, 'video'), bid.params.video); var videoObj; if (videoData !== UNDEFINED) { @@ -549,16 +549,16 @@ function _createVideoRequest(bid) { } } // read playersize and assign to h and w. - if (utils.isArray(bid.mediaTypes.video.playerSize[0])) { + if (isArray(bid.mediaTypes.video.playerSize[0])) { videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0][0], 10); videoObj.h = parseInt(bid.mediaTypes.video.playerSize[0][1], 10); - } else if (utils.isNumber(bid.mediaTypes.video.playerSize[0])) { + } else if (isNumber(bid.mediaTypes.video.playerSize[0])) { videoObj.w = parseInt(bid.mediaTypes.video.playerSize[0], 10); videoObj.h = parseInt(bid.mediaTypes.video.playerSize[1], 10); } } else { videoObj = UNDEFINED; - utils.logWarn(LOG_WARN_PREFIX + 'Error: Video config params missing for adunit: ' + bid.params.adUnit + ' with mediaType set as video. Ignoring video impression in the adunit.'); + logWarn(LOG_WARN_PREFIX + 'Error: Video config params missing for adunit: ' + bid.params.adUnit + ' with mediaType set as video. Ignoring video impression in the adunit.'); } return videoObj; } @@ -566,19 +566,19 @@ function _createVideoRequest(bid) { // support for PMP deals function _addPMPDealsInImpression(impObj, bid) { if (bid.params.deals) { - if (utils.isArray(bid.params.deals)) { + if (isArray(bid.params.deals)) { bid.params.deals.forEach(function(dealId) { - if (utils.isStr(dealId) && dealId.length > 3) { + if (isStr(dealId) && dealId.length > 3) { if (!impObj.pmp) { impObj.pmp = { private_auction: 0, deals: [] }; } impObj.pmp.deals.push({ id: dealId }); } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: deal-id present in array bid.params.deals should be a strings with more than 3 charaters length, deal-id ignored: ' + dealId); + logWarn(LOG_WARN_PREFIX + 'Error: deal-id present in array bid.params.deals should be a strings with more than 3 charaters length, deal-id ignored: ' + dealId); } }); } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: bid.params.deals should be an array of strings.'); + logWarn(LOG_WARN_PREFIX + 'Error: bid.params.deals should be an array of strings.'); } } } @@ -588,7 +588,7 @@ function _addDealCustomTargetings(imp, bid) { var dctrLen; if (bid.params.dctr) { dctr = bid.params.dctr; - if (utils.isStr(dctr) && dctr.length > 0) { + if (isStr(dctr) && dctr.length > 0) { var arr = dctr.split('|'); dctr = ''; arr.forEach(val => { @@ -600,7 +600,7 @@ function _addDealCustomTargetings(imp, bid) { } imp.ext['key_val'] = dctr.trim() } else { - utils.logWarn(LOG_WARN_PREFIX + 'Ignoring param : dctr with value : ' + dctr + ', expects string-value, found empty or non-string value'); + logWarn(LOG_WARN_PREFIX + 'Ignoring param : dctr with value : ' + dctr + ', expects string-value, found empty or non-string value'); } } } @@ -662,7 +662,7 @@ function _createImpressionObject(bid, conf) { if (!isInvalidNativeRequest) { impObj.native = nativeObj; } else { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Error in Native adunit ' + bid.params.adUnit + '. Ignoring the adunit. Refer to ' + PREBID_NATIVE_HELP_LINK + ' for more details.'); + logWarn(LOG_WARN_PREFIX + 'Error: Error in Native adunit ' + bid.params.adUnit + '. Ignoring the adunit. Refer to ' + PREBID_NATIVE_HELP_LINK + ' for more details.'); } break; case VIDEO: @@ -680,9 +680,9 @@ function _createImpressionObject(bid, conf) { pos: 0, w: bid.params.width, h: bid.params.height, - topframe: utils.inIframe() ? 0 : 1 + topframe: inIframe() ? 0 : 1 }; - if (utils.isArray(sizes) && sizes.length > 1) { + if (isArray(sizes) && sizes.length > 1) { sizes = sizes.splice(1, sizes.length - 1); sizes.forEach(size => { format.push({ @@ -705,31 +705,31 @@ function _createImpressionObject(bid, conf) { } function _addImpressionFPD(imp, bid) { - const ortb2 = {...utils.deepAccess(bid, 'ortb2Imp.ext.data')}; + const ortb2 = {...deepAccess(bid, 'ortb2Imp.ext.data')}; Object.keys(ortb2).forEach(prop => { /** * Prebid AdSlot * @type {(string|undefined)} */ if (prop === 'pbadslot') { - if (typeof ortb2[prop] === 'string' && ortb2[prop]) utils.deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]); + if (typeof ortb2[prop] === 'string' && ortb2[prop]) deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]); } else if (prop === 'adserver') { /** * Copy GAM AdUnit and Name to imp */ ['name', 'adslot'].forEach(name => { /** @type {(string|undefined)} */ - const value = utils.deepAccess(ortb2, `adserver.${name}`); + const value = deepAccess(ortb2, `adserver.${name}`); if (typeof value === 'string' && value) { - utils.deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value); + deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value); // copy GAM ad unit id as imp[].ext.dfp_ad_unit_code if (name === 'adslot') { - utils.deepSetValue(imp, `ext.dfp_ad_unit_code`, value); + deepSetValue(imp, `ext.dfp_ad_unit_code`, value); } } }); } else { - utils.deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]); + deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]); } }); } @@ -746,7 +746,7 @@ function _addFloorFromFloorModule(impObj, bid) { if (impObj[mediaType].w && impObj[mediaType].h) { sizesArray.push([impObj[mediaType].w, impObj[mediaType].h]); } - if (utils.isArray(impObj[mediaType].format)) { + if (isArray(impObj[mediaType].format)) { impObj[mediaType].format.forEach(size => sizesArray.push([size.w, size.h])); } } @@ -757,16 +757,16 @@ function _addFloorFromFloorModule(impObj, bid) { sizesArray.forEach(size => { let floorInfo = bid.getFloor({ currency: impObj.bidfloorcur, mediaType: mediaType, size: size }); - utils.logInfo(LOG_WARN_PREFIX, 'floor from floor module returned for mediatype:', mediaType, ' and size:', size, ' is: currency', floorInfo.currency, 'floor', floorInfo.floor); + logInfo(LOG_WARN_PREFIX, 'floor from floor module returned for mediatype:', mediaType, ' and size:', size, ' is: currency', floorInfo.currency, 'floor', floorInfo.floor); if (typeof floorInfo === 'object' && floorInfo.currency === impObj.bidfloorcur && !isNaN(parseInt(floorInfo.floor))) { let mediaTypeFloor = parseFloat(floorInfo.floor); - utils.logInfo(LOG_WARN_PREFIX, 'floor from floor module:', mediaTypeFloor, 'previous floor value', bidFloor, 'Min:', Math.min(mediaTypeFloor, bidFloor)); + logInfo(LOG_WARN_PREFIX, 'floor from floor module:', mediaTypeFloor, 'previous floor value', bidFloor, 'Min:', Math.min(mediaTypeFloor, bidFloor)); if (bidFloor === -1) { bidFloor = mediaTypeFloor; } else { bidFloor = Math.min(mediaTypeFloor, bidFloor) } - utils.logInfo(LOG_WARN_PREFIX, 'new floor value:', bidFloor); + logInfo(LOG_WARN_PREFIX, 'new floor value:', bidFloor); } }); } @@ -775,18 +775,18 @@ function _addFloorFromFloorModule(impObj, bid) { // get highest from impObj.bidfllor and floor from floor module // as we are using Math.max, it is ok if we have not got any floor from floorModule, then value of bidFloor will be -1 if (impObj.bidfloor) { - utils.logInfo(LOG_WARN_PREFIX, 'floor from floor module:', bidFloor, 'impObj.bidfloor', impObj.bidfloor, 'Max:', Math.max(bidFloor, impObj.bidfloor)); + logInfo(LOG_WARN_PREFIX, 'floor from floor module:', bidFloor, 'impObj.bidfloor', impObj.bidfloor, 'Max:', Math.max(bidFloor, impObj.bidfloor)); bidFloor = Math.max(bidFloor, impObj.bidfloor) } // assign value only if bidFloor is > 0 impObj.bidfloor = ((!isNaN(bidFloor) && bidFloor > 0) ? bidFloor : UNDEFINED); - utils.logInfo(LOG_WARN_PREFIX, 'new impObj.bidfloor value:', impObj.bidfloor); + logInfo(LOG_WARN_PREFIX, 'new impObj.bidfloor value:', impObj.bidfloor); } function _getFlocId(validBidRequests, flocFormat) { var flocIdObject = null; - var flocId = utils.deepAccess(validBidRequests, '0.userId.flocId'); + var flocId = deepAccess(validBidRequests, '0.userId.flocId'); if (flocId && flocId.id) { switch (flocFormat) { case FLOC_FORMAT.SEGMENT: @@ -837,7 +837,7 @@ function _handleFlocId(payload, validBidRequests) { } function _handleEids(payload, validBidRequests) { - let bidUserIdAsEids = utils.deepAccess(validBidRequests, '0.userIdAsEids'); + let bidUserIdAsEids = deepAccess(validBidRequests, '0.userIdAsEids'); let flocObject = _getFlocId(validBidRequests, FLOC_FORMAT.EID); if (flocObject) { if (!bidUserIdAsEids) { @@ -845,8 +845,8 @@ function _handleEids(payload, validBidRequests) { } bidUserIdAsEids.push(flocObject); } - if (utils.isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { - utils.deepSetValue(payload, 'user.eids', bidUserIdAsEids); + if (isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { + deepSetValue(payload, 'user.eids', bidUserIdAsEids); } } @@ -855,7 +855,7 @@ function _checkMediaType(bid, newBid) { if (bid.ext && bid.ext['BidType'] != undefined) { newBid.mediaType = MEDIATYPE[bid.ext.BidType]; } else { - utils.logInfo(LOG_WARN_PREFIX + 'bid.ext.BidType does not exist, checking alternatively for mediaType') + logInfo(LOG_WARN_PREFIX + 'bid.ext.BidType does not exist, checking alternatively for mediaType') var adm = bid.adm; var admStr = ''; var videoRegex = new RegExp(/VAST\s+version/); @@ -870,7 +870,7 @@ function _checkMediaType(bid, newBid) { newBid.mediaType = NATIVE; } } catch (e) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + adm); + logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + adm); } } } @@ -883,7 +883,7 @@ function _parseNativeResponse(bid, newBid) { try { adm = JSON.parse(bid.adm.replace(/\\/g, '')); } catch (ex) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + newBid.adm); + logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native reponse for ad response: ' + newBid.adm); return; } if (adm && adm.native && adm.native.assets && adm.native.assets.length > 0) { @@ -943,7 +943,7 @@ function _blockedIabCategoriesValidation(payload, blockedIabCategories) { if (typeof category === 'string') { // only strings return true; } else { - utils.logWarn(LOG_WARN_PREFIX + 'bcat: Each category should be a string, ignoring category: ' + category); + logWarn(LOG_WARN_PREFIX + 'bcat: Each category should be a string, ignoring category: ' + category); return false; } }) @@ -952,11 +952,11 @@ function _blockedIabCategoriesValidation(payload, blockedIabCategories) { if (category.length > 3) { return arr.indexOf(category) === index; // unique value only } else { - utils.logWarn(LOG_WARN_PREFIX + 'bcat: Each category should have a value of a length of more than 3 characters, ignoring category: ' + category) + logWarn(LOG_WARN_PREFIX + 'bcat: Each category should have a value of a length of more than 3 characters, ignoring category: ' + category) } }); if (blockedIabCategories.length > 0) { - utils.logWarn(LOG_WARN_PREFIX + 'bcat: Selected: ', blockedIabCategories); + logWarn(LOG_WARN_PREFIX + 'bcat: Selected: ', blockedIabCategories); payload.bcat = blockedIabCategories; } } @@ -979,7 +979,7 @@ function _assignRenderer(newBid, request) { } function isNonEmptyArray(test) { - if (utils.isArray(test) === true) { + if (isArray(test) === true) { if (test.length > 0) { return true; } @@ -999,27 +999,27 @@ export const spec = { */ isBidRequestValid: bid => { if (bid && bid.params) { - if (!utils.isStr(bid.params.publisherId)) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: publisherId is mandatory and cannot be numeric (wrap it in quotes in your config). Call to OpenBid will not be sent for ad unit: ' + JSON.stringify(bid)); + if (!isStr(bid.params.publisherId)) { + logWarn(LOG_WARN_PREFIX + 'Error: publisherId is mandatory and cannot be numeric (wrap it in quotes in your config). Call to OpenBid will not be sent for ad unit: ' + JSON.stringify(bid)); return false; } // video ad validation if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { // bid.mediaTypes.video.mimes OR bid.params.video.mimes should be present and must be a non-empty array - let mediaTypesVideoMimes = utils.deepAccess(bid.mediaTypes, 'video.mimes'); - let paramsVideoMimes = utils.deepAccess(bid, 'params.video.mimes'); + let mediaTypesVideoMimes = deepAccess(bid.mediaTypes, 'video.mimes'); + let paramsVideoMimes = deepAccess(bid, 'params.video.mimes'); if (isNonEmptyArray(mediaTypesVideoMimes) === false && isNonEmptyArray(paramsVideoMimes) === false) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: For video ads, bid.mediaTypes.video.mimes OR bid.params.video.mimes should be present and must be a non-empty array. Call to OpenBid will not be sent for ad unit:' + JSON.stringify(bid)); + logWarn(LOG_WARN_PREFIX + 'Error: For video ads, bid.mediaTypes.video.mimes OR bid.params.video.mimes should be present and must be a non-empty array. Call to OpenBid will not be sent for ad unit:' + JSON.stringify(bid)); return false; } if (!bid.mediaTypes[VIDEO].hasOwnProperty('context')) { - utils.logError(`${LOG_WARN_PREFIX}: no context specified in bid. Rejecting bid: `, bid); + logError(`${LOG_WARN_PREFIX}: no context specified in bid. Rejecting bid: `, bid); return false; } if (bid.mediaTypes[VIDEO].context === 'outstream' && - !utils.isStr(bid.params.outstreamAU) && + !isStr(bid.params.outstreamAU) && !bid.hasOwnProperty('renderer') && !bid.mediaTypes[VIDEO].hasOwnProperty('renderer')) { // we are here since outstream ad-unit is provided without outstreamAU and renderer @@ -1029,10 +1029,10 @@ export const spec = { if (bid.mediaTypes.hasOwnProperty(BANNER) || bid.mediaTypes.hasOwnProperty(NATIVE)) { delete bid.mediaTypes[VIDEO]; - utils.logWarn(`${LOG_WARN_PREFIX}: for "outstream" bids either outstreamAU parameter must be provided or ad unit supplied renderer is required. Rejecting mediatype Video of bid: `, bid); + logWarn(`${LOG_WARN_PREFIX}: for "outstream" bids either outstreamAU parameter must be provided or ad unit supplied renderer is required. Rejecting mediatype Video of bid: `, bid); return true; } else { - utils.logError(`${LOG_WARN_PREFIX}: for "outstream" bids either outstreamAU parameter must be provided or ad unit supplied renderer is required. Rejecting bid: `, bid); + logError(`${LOG_WARN_PREFIX}: for "outstream" bids either outstreamAU parameter must be provided or ad unit supplied renderer is required. Rejecting bid: `, bid); return false; } } @@ -1061,7 +1061,7 @@ export const spec = { var blockedIabCategories = []; validBidRequests.forEach(originalBid => { - bid = utils.deepClone(originalBid); + bid = deepClone(originalBid); bid.params.adSlot = bid.params.adSlot || ''; _parseAdSlot(bid); if (bid.params.hasOwnProperty('video')) { @@ -1070,7 +1070,7 @@ export const spec = { // If we have a native mediaType configured alongside banner, its ok if the banner size is not set in width and height // The corresponding banner imp object will not be generated, but we still want the native object to be sent, hence the following check if (!(bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(NATIVE)) && bid.params.width === 0 && bid.params.height === 0) { - utils.logWarn(LOG_WARN_PREFIX + 'Skipping the non-standard adslot: ', bid.params.adSlot, JSON.stringify(bid)); + logWarn(LOG_WARN_PREFIX + 'Skipping the non-standard adslot: ', bid.params.adSlot, JSON.stringify(bid)); return; } } @@ -1080,14 +1080,14 @@ export const spec = { if (bidCurrency === '') { bidCurrency = bid.params.currency || UNDEFINED; } else if (bid.params.hasOwnProperty('currency') && bidCurrency !== bid.params.currency) { - utils.logWarn(LOG_WARN_PREFIX + 'Currency specifier ignored. Only one currency permitted.'); + logWarn(LOG_WARN_PREFIX + 'Currency specifier ignored. Only one currency permitted.'); } bid.params.currency = bidCurrency; // check if dctr is added to more than 1 adunit - if (bid.params.hasOwnProperty('dctr') && utils.isStr(bid.params.dctr)) { + if (bid.params.hasOwnProperty('dctr') && isStr(bid.params.dctr)) { dctrArr.push(bid.params.dctr); } - if (bid.params.hasOwnProperty('bcat') && utils.isArray(bid.params.bcat)) { + if (bid.params.hasOwnProperty('bcat') && isArray(bid.params.bcat)) { blockedIabCategories = blockedIabCategories.concat(bid.params.bcat); } var impObj = _createImpressionObject(bid, conf); @@ -1130,7 +1130,7 @@ export const spec = { } // passing transactionId in source.tid - utils.deepSetValue(payload, 'source.tid', conf.transactionId); + deepSetValue(payload, 'source.tid', conf.transactionId); // test bids if (window.location.href.indexOf('pubmaticTest=true') !== -1) { @@ -1139,23 +1139,23 @@ export const spec = { // adding schain object if (validBidRequests[0].schain) { - utils.deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); + deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); } // Attaching GDPR Consent Params if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); } // CCPA if (bidderRequest && bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } // coppa compliance if (config.getConfig('coppa') === true) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } _handleEids(payload, validBidRequests); @@ -1164,10 +1164,10 @@ export const spec = { // First Party Data const commonFpd = config.getConfig('ortb2') || {}; if (commonFpd.site) { - utils.mergeDeep(payload, {site: commonFpd.site}); + mergeDeep(payload, {site: commonFpd.site}); } if (commonFpd.user) { - utils.mergeDeep(payload, {user: commonFpd.user}); + mergeDeep(payload, {user: commonFpd.user}); } // Note: Do not move this block up @@ -1205,12 +1205,12 @@ export const spec = { let parsedRequest = JSON.parse(request.data); let parsedReferrer = parsedRequest.site && parsedRequest.site.ref ? parsedRequest.site.ref : ''; try { - if (response.body && response.body.seatbid && utils.isArray(response.body.seatbid)) { + if (response.body && response.body.seatbid && isArray(response.body.seatbid)) { // Supporting multiple bid responses for same adSize respCur = response.body.cur || respCur; response.body.seatbid.forEach(seatbidder => { seatbidder.bid && - utils.isArray(seatbidder.bid) && + isArray(seatbidder.bid) && seatbidder.bid.forEach(bid => { let newBid = { requestId: bid.impid, @@ -1276,7 +1276,7 @@ export const spec = { }); } } catch (error) { - utils.logError(error); + logError(error); } return bidResponses; }, @@ -1323,7 +1323,7 @@ export const spec = { * @return {Object} params bid params */ transformBidParams: function (params, isOpenRtb) { - return utils.convertTypes({ + return convertTypes({ 'publisherId': 'string', 'adSlot': 'string' }, params); diff --git a/modules/pubperfAnalyticsAdapter.js b/modules/pubperfAnalyticsAdapter.js index 800ea1cd550..9282d5814c0 100644 --- a/modules/pubperfAnalyticsAdapter.js +++ b/modules/pubperfAnalyticsAdapter.js @@ -4,7 +4,7 @@ import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; +import { logError } from '../src/utils.js'; var pubperfAdapter = adapter({ global: 'pubperf_pbjs', @@ -16,11 +16,11 @@ pubperfAdapter.originEnableAnalytics = pubperfAdapter.enableAnalytics; pubperfAdapter.enableAnalytics = config => { if (!config || !config.provider || config.provider !== 'pubperf') { - utils.logError('expected config.provider to equal pubperf'); + logError('expected config.provider to equal pubperf'); return; } if (!window['pubperf_pbjs']) { - utils.logError( + logError( `Make sure that Pubperf tag from https://www.pubperf.com is included before the Prebid configuration.` ); return; diff --git a/modules/pubwiseAnalyticsAdapter.js b/modules/pubwiseAnalyticsAdapter.js index fe217454b88..006d6da7eb7 100644 --- a/modules/pubwiseAnalyticsAdapter.js +++ b/modules/pubwiseAnalyticsAdapter.js @@ -1,9 +1,9 @@ +import { getParameterByName, logInfo, generateUUID, debugTurnedOn } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; import { getStorageManager } from '../src/storageManager.js'; -const utils = require('../src/utils.js'); const storage = getStorageManager(); /**** @@ -76,7 +76,7 @@ function enrichWithUTM(dataBag) { let newUtm = false; try { for (let prop in utmKeys) { - utmKeys[prop] = utils.getParameterByName(prop); + utmKeys[prop] = getParameterByName(prop); if (utmKeys[prop]) { newUtm = true; dataBag[prop] = utmKeys[prop]; @@ -192,7 +192,7 @@ function markEnabled() { } function pwInfo(info, context) { - utils.logInfo(`${analyticsName} ` + info, context); + logInfo(`${analyticsName} ` + info, context); } function filterBidResponse(data) { @@ -304,7 +304,7 @@ pubwiseAnalytics.storeSessionID = function (userSessID) { // ensure a session exists, if not make one, always store it pubwiseAnalytics.ensureSession = function () { if (sessionExpired() === true || userSessionID() === null || userSessionID() === '') { - let generatedId = utils.generateUUID(); + let generatedId = generateUUID(); expireUtmData(); this.storeSessionID(generatedId); sessionData.sessionId = generatedId; @@ -320,10 +320,10 @@ pubwiseAnalytics.enableAnalytics = function (config) { configOptions = Object.assign(configOptions, config.options); // take the PBJS debug for our debug setting if no PW debug is defined if (configOptions.debug === null) { - configOptions.debug = utils.debugTurnedOn(); + configOptions.debug = debugTurnedOn(); } markEnabled(); - sessionData.activationId = utils.generateUUID(); + sessionData.activationId = generateUUID(); this.ensureSession(); pubwiseAnalytics.adapterEnableAnalytics(config); }; diff --git a/modules/pubwiseBidAdapter.js b/modules/pubwiseBidAdapter.js index f450a8bede8..a1b9ffb56a0 100644 --- a/modules/pubwiseBidAdapter.js +++ b/modules/pubwiseBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { _each, isStr, deepClone, isArray, deepSetValue, inIframe, logMessage, logInfo, logWarn, logError } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; @@ -81,9 +81,9 @@ let NATIVE_ASSET_KEY_TO_ASSET_MAP = {}; // together allows traversal of NATIVE_ASSETS_LIST in any direction // id -> key -utils._each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); +_each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); // key -> asset -utils._each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); +_each(NATIVE_ASSETS, anAsset => { NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); export const spec = { code: BIDDER_CODE, @@ -99,7 +99,7 @@ export const spec = { // siteId is required if (bid.params && bid.params.siteId) { // it must be a string - if (!utils.isStr(bid.params.siteId)) { + if (!isStr(bid.params.siteId)) { _logWarn('siteId is required for bid', bid); return false; } @@ -127,7 +127,7 @@ export const spec = { var blockedIabCategories = []; validBidRequests.forEach(originalBid => { - bid = utils.deepClone(originalBid); + bid = deepClone(originalBid); bid.params.adSlot = bid.params.adSlot || ''; _parseAdSlot(bid); @@ -136,7 +136,7 @@ export const spec = { bidCurrency = bid.params.currency || UNDEFINED; bid.params.currency = bidCurrency; - if (bid.params.hasOwnProperty('bcat') && utils.isArray(bid.params.bcat)) { + if (bid.params.hasOwnProperty('bcat') && isArray(bid.params.bcat)) { blockedIabCategories = blockedIabCategories.concat(bid.params.bcat); } @@ -180,27 +180,27 @@ export const spec = { } // passing transactionId in source.tid - utils.deepSetValue(payload, 'source.tid', conf.transactionId); + deepSetValue(payload, 'source.tid', conf.transactionId); // schain if (validBidRequests[0].schain) { - utils.deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); + deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); } // gdpr consent if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); } // ccpa on the root object if (bidderRequest && bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } // if coppa is in effect then note it if (config.getConfig('coppa') === true) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } var options = {contentType: 'text/plain'} @@ -230,12 +230,12 @@ export const spec = { // let parsedReferrer = parsedRequest.site && parsedRequest.site.ref ? parsedRequest.site.ref : ''; // try { - if (response.body && response.body.seatbid && utils.isArray(response.body.seatbid)) { + if (response.body && response.body.seatbid && isArray(response.body.seatbid)) { // Supporting multiple bid responses for same adSize respCur = response.body.cur || respCur; response.body.seatbid.forEach(seatbidder => { seatbidder.bid && - utils.isArray(seatbidder.bid) && + isArray(seatbidder.bid) && seatbidder.bid.forEach(bid => { let newBid = { requestId: bid.impid, @@ -388,7 +388,7 @@ function _handleCustomParams(params, conf) { value = entry.f(value, conf); } - if (utils.isStr(value)) { + if (isStr(value)) { conf[key] = value; } else { _logWarn('Ignoring param : ' + key + ' with value : ' + CUSTOM_PARAMS[key] + ', expects string-value, found ' + typeof value); @@ -469,7 +469,7 @@ function _createImpressionObject(bid, conf) { } function _parseSlotParam(paramName, paramValue) { - if (!utils.isStr(paramValue)) { + if (!isStr(paramValue)) { paramValue && _logWarn('Ignoring param key: ' + paramName + ', expects string-value, found ' + typeof paramValue); return UNDEFINED; } @@ -520,7 +520,7 @@ function _parseAdSlot(bid) { } function _cleanSlotName(slotName) { - if (utils.isStr(slotName)) { + if (isStr(slotName)) { return slotName.replace(/^\s+/g, '').replace(/\s+$/g, ''); } return ''; @@ -705,7 +705,7 @@ function _createBannerRequest(bid) { var sizes = bid.mediaTypes.banner.sizes; var format = []; var bannerObj; - if (sizes !== UNDEFINED && utils.isArray(sizes)) { + if (sizes !== UNDEFINED && isArray(sizes)) { bannerObj = {}; if (!bid.params.width && !bid.params.height) { if (sizes.length === 0) { @@ -734,7 +734,7 @@ function _createBannerRequest(bid) { } } bannerObj.pos = 0; - bannerObj.topframe = utils.inIframe() ? 0 : 1; + bannerObj.topframe = inIframe() ? 0 : 1; } else { _logWarn('Error: mediaTypes.banner.size missing for adunit: ' + bid.params.adUnit + '. Ignoring the banner impression in the adunit.'); bannerObj = UNDEFINED; @@ -745,22 +745,22 @@ function _createBannerRequest(bid) { // various error levels are not always used // eslint-disable-next-line no-unused-vars function _logMessage(textValue, objectValue) { - utils.logMessage('PubWise: ' + textValue, objectValue); + logMessage('PubWise: ' + textValue, objectValue); } // eslint-disable-next-line no-unused-vars function _logInfo(textValue, objectValue) { - utils.logInfo('PubWise: ' + textValue, objectValue); + logInfo('PubWise: ' + textValue, objectValue); } // eslint-disable-next-line no-unused-vars function _logWarn(textValue, objectValue) { - utils.logWarn('PubWise: ' + textValue, objectValue); + logWarn('PubWise: ' + textValue, objectValue); } // eslint-disable-next-line no-unused-vars function _logError(textValue, objectValue) { - utils.logError('PubWise: ' + textValue, objectValue); + logError('PubWise: ' + textValue, objectValue); } // function _decorateLog() { diff --git a/modules/pubxBidAdapter.js b/modules/pubxBidAdapter.js index c7b63d3f7f7..18d2bb11404 100644 --- a/modules/pubxBidAdapter.js +++ b/modules/pubxBidAdapter.js @@ -1,5 +1,5 @@ +import { deepSetValue } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'pubx'; const BID_ENDPOINT = 'https://api.primecaster.net/adlogue/api/slot/bid'; @@ -43,7 +43,7 @@ export const spec = { ad: body.adm }; if (body.adomains) { - utils.deepSetValue(bidResponse, 'meta.advertiserDomains', Array.isArray(body.adomains) ? body.adomains : [body.adomains]); + deepSetValue(bidResponse, 'meta.advertiserDomains', Array.isArray(body.adomains) ? body.adomains : [body.adomains]); } bidResponses.push(bidResponse); } else {}; diff --git a/modules/pubxaiAnalyticsAdapter.js b/modules/pubxaiAnalyticsAdapter.js index 98b4dec1dca..3232d34ccba 100644 --- a/modules/pubxaiAnalyticsAdapter.js +++ b/modules/pubxaiAnalyticsAdapter.js @@ -1,8 +1,8 @@ +import { deepAccess, getGptSlotInfoForAdUnitCode, parseSizesInput, getWindowLocation, buildUrl } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; const emptyUrl = ''; const analyticsType = 'endpoint'; @@ -34,7 +34,7 @@ var pubxaiAnalyticsAdapter = Object.assign(adapter( events.auctionInit = args; events.floorDetail = {}; events.bids = []; - const floorData = utils.deepAccess(args, 'bidderRequests.0.bids.0.floorData'); + const floorData = deepAccess(args, 'bidderRequests.0.bids.0.floorData'); if (typeof floorData !== 'undefined') { Object.assign(events.floorDetail, floorData); } @@ -57,7 +57,7 @@ function mapBidResponse(bidResponse, status) { if (typeof bidResponse !== 'undefined') { let bid = { adUnitCode: bidResponse.adUnitCode, - gptSlotCode: utils.getGptSlotInfoForAdUnitCode(bidResponse.adUnitCode).gptSlot || null, + gptSlotCode: getGptSlotInfoForAdUnitCode(bidResponse.adUnitCode).gptSlot || null, auctionId: bidResponse.auctionId, bidderCode: bidResponse.bidder, cpm: bidResponse.cpm, @@ -77,7 +77,7 @@ function mapBidResponse(bidResponse, status) { Object.assign(bid, { bidId: status === 'timeout' ? bidResponse.bidId : bidResponse.requestId, renderStatus: status === 'timeout' ? 3 : 2, - sizes: utils.parseSizesInput(bidResponse.size).toString(), + sizes: parseSizesInput(bidResponse.size).toString(), }); events.bids.push(bid); } else { @@ -85,7 +85,7 @@ function mapBidResponse(bidResponse, status) { bidId: bidResponse.requestId, floorProvider: events.floorDetail ? events.floorDetail.floorProvider : null, isWinningBid: true, - placementId: bidResponse.params ? utils.deepAccess(bidResponse, 'params.0.placementId') : null, + placementId: bidResponse.params ? deepAccess(bidResponse, 'params.0.placementId') : null, renderedSize: bidResponse.size, renderStatus: 4 }); @@ -131,7 +131,7 @@ pubxaiAnalyticsAdapter.shouldFireEventRequest = function (samplingRate = 1) { function send(data, status) { if (pubxaiAnalyticsAdapter.shouldFireEventRequest(initOptions.samplingRate)) { - let location = utils.getWindowLocation(); + let location = getWindowLocation(); data.initOptions = initOptions; if (typeof data !== 'undefined' && typeof data.auctionInit !== 'undefined') { Object.assign(data.pageDetail, { @@ -150,7 +150,7 @@ function send(data, status) { deviceOS: getOS(), browser: getBrowser() }); - let pubxaiAnalyticsRequestUrl = utils.buildUrl({ + let pubxaiAnalyticsRequestUrl = buildUrl({ protocol: 'https', hostname: (initOptions && initOptions.hostName) || defaultHost, pathname: status == 'bidwon' ? winningBidPath : auctionPath, diff --git a/modules/pulsepointBidAdapter.js b/modules/pulsepointBidAdapter.js index 5f8f096926b..7aa3ad6088c 100644 --- a/modules/pulsepointBidAdapter.js +++ b/modules/pulsepointBidAdapter.js @@ -1,5 +1,5 @@ /* eslint dot-notation:0, quote-props:0 */ -import * as utils from '../src/utils.js'; +import { convertTypes, deepAccess, isArray, logError, isFn } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { Renderer } from '../src/Renderer.js'; @@ -77,7 +77,7 @@ export const spec = { } }, transformBidParams: function(params, isOpenRtb) { - return utils.convertTypes({ + return convertTypes({ 'cf': 'string', 'cp': 'number', 'ct': 'number' @@ -124,8 +124,8 @@ function bidResponseAvailable(request, response) { }; if (idToImpMap[id].video) { // for outstream, a renderer is specified - if (idToSlotConfig[id] && utils.deepAccess(idToSlotConfig[id], 'mediaTypes.video.context') === 'outstream') { - bid.renderer = outstreamRenderer(utils.deepAccess(idToSlotConfig[id], 'renderer.options'), utils.deepAccess(idToBidMap[id], 'ext.outstream')); + if (idToSlotConfig[id] && deepAccess(idToSlotConfig[id], 'mediaTypes.video.context') === 'outstream') { + bid.renderer = outstreamRenderer(deepAccess(idToSlotConfig[id], 'renderer.options'), deepAccess(idToBidMap[id], 'ext.outstream')); } bid.vastXml = idToBidMap[id].adm; bid.mediaType = 'video'; @@ -178,9 +178,9 @@ function banner(slot) { * Produce openrtb format objects based on the sizes configured for the slot. */ function parseSizes(slot) { - const sizes = utils.deepAccess(slot, 'mediaTypes.banner.sizes'); - if (sizes && utils.isArray(sizes)) { - return sizes.filter(sz => utils.isArray(sz) && sz.length === 2).map(sz => ({ + const sizes = deepAccess(slot, 'mediaTypes.banner.sizes'); + if (sizes && isArray(sizes)) { + return sizes.filter(sz => isArray(sz) && sz.length === 2).map(sz => ({ w: sz[0], h: sz[1] })); @@ -387,7 +387,7 @@ function parse(rawResponse) { return JSON.parse(rawResponse); } } catch (ex) { - utils.logError('pulsepointLite.safeParse', 'ERROR', ex); + logError('pulsepointLite.safeParse', 'ERROR', ex); } return null; } @@ -425,14 +425,14 @@ function user(bidRequest, bidderRequest) { addExternalUserId(ext.eids, bidRequest.userId.britepoolid, 'britepool.com'); addExternalUserId(ext.eids, bidRequest.userId.criteoId, 'criteo.com'); addExternalUserId(ext.eids, bidRequest.userId.idl_env, 'liveramp.com'); - addExternalUserId(ext.eids, utils.deepAccess(bidRequest, 'userId.id5id.uid'), 'id5-sync.com', utils.deepAccess(bidRequest, 'userId.id5id.ext')); - addExternalUserId(ext.eids, utils.deepAccess(bidRequest, 'userId.parrableId.eid'), 'parrable.com'); + addExternalUserId(ext.eids, deepAccess(bidRequest, 'userId.id5id.uid'), 'id5-sync.com', deepAccess(bidRequest, 'userId.id5id.ext')); + addExternalUserId(ext.eids, deepAccess(bidRequest, 'userId.parrableId.eid'), 'parrable.com'); addExternalUserId(ext.eids, bidRequest.userId.fabrickId, 'neustar.biz'); - addExternalUserId(ext.eids, utils.deepAccess(bidRequest, 'userId.haloId.haloId'), 'audigent.com'); + addExternalUserId(ext.eids, deepAccess(bidRequest, 'userId.haloId.haloId'), 'audigent.com'); addExternalUserId(ext.eids, bidRequest.userId.merkleId, 'merkleinc.com'); addExternalUserId(ext.eids, bidRequest.userId.lotamePanoramaId, 'crwdcntrl.net'); addExternalUserId(ext.eids, bidRequest.userId.connectid, 'verizonmedia.com'); - addExternalUserId(ext.eids, utils.deepAccess(bidRequest, 'userId.uid2.id'), 'uidapi.com'); + addExternalUserId(ext.eids, deepAccess(bidRequest, 'userId.uid2.id'), 'uidapi.com'); // liveintent if (bidRequest.userId.lipb && bidRequest.userId.lipb.lipbid) { addExternalUserId(ext.eids, bidRequest.userId.lipb.lipbid, 'liveintent.com'); @@ -532,7 +532,7 @@ function nativeResponse(imp, bid) { function bidFloor(slot) { let floor = slot.params.bidfloor; - if (utils.isFn(slot.getFloor)) { + if (isFn(slot.getFloor)) { const floorData = slot.getFloor({ mediaType: slot.mediaTypes.banner ? 'banner' : slot.mediaTypes.video ? 'video' : 'Native', size: '*', diff --git a/modules/pxyzBidAdapter.js b/modules/pxyzBidAdapter.js index 9baff4d1533..e144eb84a01 100644 --- a/modules/pxyzBidAdapter.js +++ b/modules/pxyzBidAdapter.js @@ -1,6 +1,6 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { logInfo, logError, isArray } from '../src/utils.js'; const BIDDER_CODE = 'pxyz'; const URL = 'https://ads.playground.xyz/host-config/prebid?v=2'; @@ -61,15 +61,15 @@ export const spec = { if (bidderRequest && bidderRequest.gdprConsent) { const gdpr = bidderRequest.gdprConsent.gdprApplies ? 1 : 0; const consentString = bidderRequest.gdprConsent.consentString; - utils.logInfo(`PXYZ: GDPR applies ${gdpr}`); - utils.logInfo(`PXYZ: GDPR consent string ${consentString}`); + logInfo(`PXYZ: GDPR applies ${gdpr}`); + logInfo(`PXYZ: GDPR consent string ${consentString}`); payload.Regs.ext.gdpr = gdpr; payload.User = { ext: { consent: consentString } }; } // CCPA if (bidderRequest && bidderRequest.uspConsent) { - utils.logInfo(`PXYZ: USP Consent ${bidderRequest.uspConsent}`); + logInfo(`PXYZ: USP Consent ${bidderRequest.uspConsent}`); payload.Regs.ext['us_privacy'] = bidderRequest.uspConsent; } @@ -95,14 +95,14 @@ export const spec = { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`; if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; - utils.logError(errorMessage); + logError(errorMessage); } return bids; } - if (!utils.isArray(serverResponse.seatbid)) { + if (!isArray(serverResponse.seatbid)) { let errorMessage = `in response for ${bidderRequest.bidderCode} adapter `; - utils.logError(errorMessage += 'Malformed seatbid response'); + logError(errorMessage += 'Malformed seatbid response'); return bids; } diff --git a/modules/quantcastBidAdapter.js b/modules/quantcastBidAdapter.js index ecb5ad3176e..e168339426d 100644 --- a/modules/quantcastBidAdapter.js +++ b/modules/quantcastBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, logInfo, logError, isEmpty, isArray } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { config } from '../src/config.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -24,8 +24,8 @@ export const QUANTCAST_FPA = '__qca'; export const storage = getStorageManager(QUANTCAST_VENDOR_ID, BIDDER_CODE); function makeVideoImp(bid) { - const videoInMediaType = utils.deepAccess(bid, 'mediaTypes.video') || {}; - const videoInParams = utils.deepAccess(bid, 'params.video') || {}; + const videoInMediaType = deepAccess(bid, 'mediaTypes.video') || {}; + const videoInParams = deepAccess(bid, 'params.video') || {}; const video = Object.assign({}, videoInParams, videoInMediaType); if (video.playerSize) { @@ -142,10 +142,10 @@ export const spec = { */ buildRequests(bidRequests, bidderRequest) { const bids = bidRequests || []; - const gdprConsent = utils.deepAccess(bidderRequest, 'gdprConsent') || {}; - const uspConsent = utils.deepAccess(bidderRequest, 'uspConsent'); - const referrer = utils.deepAccess(bidderRequest, 'refererInfo.referer'); - const page = utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || utils.deepAccess(window, 'location.href'); + const gdprConsent = deepAccess(bidderRequest, 'gdprConsent') || {}; + const uspConsent = deepAccess(bidderRequest, 'uspConsent'); + const referrer = deepAccess(bidderRequest, 'refererInfo.referer'); + const page = deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || config.getConfig('pageUrl') || deepAccess(window, 'location.href'); const domain = getDomain(page); // Check for GDPR consent for purpose 1, and drop request if consent has not been given @@ -153,11 +153,11 @@ export const spec = { if (gdprConsent.gdprApplies) { if (gdprConsent.vendorData) { if (gdprConsent.apiVersion === 1 && !checkTCFv1(gdprConsent.vendorData)) { - utils.logInfo(`${BIDDER_CODE}: No purpose 1 consent for TCF v1`); + logInfo(`${BIDDER_CODE}: No purpose 1 consent for TCF v1`); return; } if (gdprConsent.apiVersion === 2 && !checkTCFv2(gdprConsent.vendorData)) { - utils.logInfo(`${BIDDER_CODE}: No purpose 1 consent for TCF v2`); + logInfo(`${BIDDER_CODE}: No purpose 1 consent for TCF v2`); return; } } @@ -174,7 +174,7 @@ export const spec = { imp = makeBannerImp(bid); } else { // Unsupported mediaType - utils.logInfo(`${BIDDER_CODE}: No supported mediaTypes found in ${JSON.stringify(bid.mediaTypes)}`); + logInfo(`${BIDDER_CODE}: No supported mediaTypes found in ${JSON.stringify(bid.mediaTypes)}`); return; } } else { @@ -231,18 +231,18 @@ export const spec = { */ interpretResponse(serverResponse) { if (serverResponse === undefined) { - utils.logError('Server Response is undefined'); + logError('Server Response is undefined'); return []; } const response = serverResponse['body']; if (response === undefined || !response.hasOwnProperty('bids')) { - utils.logError('Sub-optimal JSON received from Quantcast server'); + logError('Sub-optimal JSON received from Quantcast server'); return []; } - if (utils.isEmpty(response.bids)) { + if (isEmpty(response.bids)) { // Shortcut response handling if no bids are present return []; } @@ -271,7 +271,7 @@ export const spec = { result['dealId'] = dealId; } - if (meta !== undefined && meta.advertiserDomains && utils.isArray(meta.advertiserDomains)) { + if (meta !== undefined && meta.advertiserDomains && isArray(meta.advertiserDomains)) { result.meta = {}; result.meta.advertiserDomains = meta.advertiserDomains; } @@ -289,11 +289,11 @@ export const spec = { const syncs = [] if (!hasUserSynced && syncOptions.pixelEnabled) { const responseWithUrl = find(serverResponses, serverResponse => - utils.deepAccess(serverResponse.body, 'userSync.url') + deepAccess(serverResponse.body, 'userSync.url') ); if (responseWithUrl) { - const url = utils.deepAccess(responseWithUrl.body, 'userSync.url') + const url = deepAccess(responseWithUrl.body, 'userSync.url') syncs.push({ type: 'image', url: url diff --git a/modules/radsBidAdapter.js b/modules/radsBidAdapter.js index 5cc88440629..fee5daa3fb4 100644 --- a/modules/radsBidAdapter.js +++ b/modules/radsBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -216,7 +216,7 @@ function prepareExtraParams(params, payload, bidderRequest, bidRequest) { * @returns {boolean} True if it's a banner bid */ function isBannerRequest(bid) { - return bid.mediaType === 'banner' || !!utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoRequest(bid); + return bid.mediaType === 'banner' || !!deepAccess(bid, 'mediaTypes.banner') || !isVideoRequest(bid); } /** @@ -226,7 +226,7 @@ function isBannerRequest(bid) { * @returns {boolean} True if it's a video bid */ function isVideoRequest(bid) { - return bid.mediaType === 'video' || !!utils.deepAccess(bid, 'mediaTypes.video'); + return bid.mediaType === 'video' || !!deepAccess(bid, 'mediaTypes.video'); } /** @@ -236,7 +236,7 @@ function isVideoRequest(bid) { * @returns {object} True if it's a video bid */ function getVideoSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } /** @@ -246,7 +246,7 @@ function getVideoSizes(bid) { * @returns {object} True if it's a video bid */ function getBannerSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } /** From f0be8816095d91ddac4ed9fc11fb4673ad9bf42f Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 10:56:56 -0700 Subject: [PATCH 27/84] PBjs Core: use GPT's slot.updateTargetingFromMap instead of slot.setTargeting (Issue #7416) (#7453) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * using GPT's slot.updateTargetingFromMap instead of slot.setTargeting tests are failing; need to fix tests * now tests are passing * tests passsing now * modified the check for splitting the string * added some explanation in comment * code review suggestions --- src/targeting.js | 23 ++++++++++------------- test/spec/unit/pbjs_api_spec.js | 4 ++++ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/targeting.js b/src/targeting.js index 96692376d82..ce519f8add3 100644 --- a/src/targeting.js +++ b/src/targeting.js @@ -379,21 +379,18 @@ export function newTargeting(auctionManager) { targeting.setTargetingForGPT = function(targetingConfig, customSlotMatching) { window.googletag.pubads().getSlots().forEach(slot => { Object.keys(targetingConfig).filter(customSlotMatching ? customSlotMatching(slot) : isAdUnitCodeMatchingSlot(slot)) - .forEach(targetId => + .forEach(targetId => { Object.keys(targetingConfig[targetId]).forEach(key => { - let valueArr = targetingConfig[targetId][key]; - if (typeof valueArr === 'string') { - valueArr = valueArr.split(','); + let value = targetingConfig[targetId][key]; + if (typeof value === 'string' && value.indexOf(',') !== -1) { + // due to the check the array will be formed only if string has ',' else plain string will be assigned as value + value = value.split(','); } - valueArr = (valueArr.length > 1) ? [valueArr] : valueArr; - valueArr.map((value) => { - utils.logMessage(`Attempting to set key value for slot: ${slot.getSlotElementId()} key: ${key} value: ${value}`); - return value; - }).forEach(value => { - slot.setTargeting(key, value); - }); - }) - ) + targetingConfig[targetId][key] = value; + }); + utils.logMessage(`Attempting to set targeting-map for slot: ${slot.getSlotElementId()} with targeting-map:`, targetingConfig[targetId]); + slot.updateTargetingFromMap(targetingConfig[targetId]) + }) }) }; diff --git a/test/spec/unit/pbjs_api_spec.js b/test/spec/unit/pbjs_api_spec.js index 199ce699dc8..cc75b95a7ac 100644 --- a/test/spec/unit/pbjs_api_spec.js +++ b/test/spec/unit/pbjs_api_spec.js @@ -75,6 +75,10 @@ var Slot = function Slot(elementId, pathId) { clearTargeting: function clearTargeting() { this.targeting = {}; return this; + }, + + updateTargetingFromMap: function updateTargetingFromMap(targetingMap) { + Object.keys(targetingMap).forEach(key => this.setTargeting(key, targetingMap[key])) } }; slot.spySetTargeting = sinon.spy(slot, 'setTargeting'); From 38c353a04994806c55ad50179a76bb37b94608ea Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 11:46:24 -0700 Subject: [PATCH 28/84] Multiple Bid/Analytics/ID Adapters: import utils functions as needed and not the whole module (#7483) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/datablocksBidAdapter.js | 24 +++++++-------- modules/deepintentBidAdapter.js | 26 ++++++++-------- modules/dgkeywordRtdProvider.js | 20 ++++++------ modules/districtmDMXBidAdapter.js | 30 +++++++++--------- modules/dmdIdSystem.js | 10 +++--- modules/docereeBidAdapter.js | 18 +++++------ modules/dspxBidAdapter.js | 10 +++--- modules/ebdrBidAdapter.js | 18 +++++------ modules/emx_digitalBidAdapter.js | 46 ++++++++++++++-------------- modules/enrichmentFpdModule.js | 19 ++++++------ modules/eplanningAnalyticsAdapter.js | 4 +-- modules/eplanningBidAdapter.js | 14 ++++----- modules/etargetBidAdapter.js | 8 ++--- modules/express.js | 19 ++++++------ modules/fabrickIdSystem.js | 12 ++++---- 15 files changed, 139 insertions(+), 139 deletions(-) diff --git a/modules/datablocksBidAdapter.js b/modules/datablocksBidAdapter.js index bfbe7a16fc6..197ba19b1d6 100644 --- a/modules/datablocksBidAdapter.js +++ b/modules/datablocksBidAdapter.js @@ -1,6 +1,6 @@ +import { getWindowTop, isGptPubadsDefined, deepAccess, getAdUnitSizes, isEmpty } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; import { getStorageManager } from '../src/storageManager.js'; import { ajax } from '../src/ajax.js'; @@ -199,7 +199,7 @@ export const spec = { // GET BASIC CLIENT INFORMATION get_client_info: function () { let botTest = new BotClientTests(); - let win = utils.getWindowTop(); + let win = getWindowTop(); return { 'wiw': win.innerWidth, 'wih': win.innerHeight, @@ -226,7 +226,7 @@ export const spec = { // ADD GPT EVENT LISTENERS let scope = this; - if (utils.isGptPubadsDefined()) { + if (isGptPubadsDefined()) { if (typeof window['googletag'].pubads().addEventListener == 'function') { window['googletag'].pubads().addEventListener('impressionViewable', function(event) { scope.queue_metric({type: 'slot_view', source_id: scope.db_obj.source_id, auction_id: bid.auctionId, div_id: event.slot.getSlotElementId(), slot_id: event.slot.getSlotId().getAdUnitPath()}); @@ -306,7 +306,7 @@ export const spec = { tagid: bidRequest.params.tagid || bidRequest.adUnitCode, placement_id: bidRequest.params.placement_id || 0, secure: window.location.protocol == 'https:', - ortb2: utils.deepAccess(bidRequest, `ortb2Imp`) || {}, + ortb2: deepAccess(bidRequest, `ortb2Imp`) || {}, floor: {} } @@ -320,8 +320,8 @@ export const spec = { } // BUILD THE SIZES - if (utils.deepAccess(bidRequest, `mediaTypes.banner`)) { - let sizes = utils.getAdUnitSizes(bidRequest); + if (deepAccess(bidRequest, `mediaTypes.banner`)) { + let sizes = getAdUnitSizes(bidRequest); if (sizes.length) { imp.banner = { w: sizes[0][0], @@ -332,7 +332,7 @@ export const spec = { // ADD TO THE LIST OF IMP REQUESTS imps.push(imp); } - } else if (utils.deepAccess(bidRequest, `mediaTypes.native`)) { + } else if (deepAccess(bidRequest, `mediaTypes.native`)) { // ADD TO THE LIST OF IMP REQUESTS imp.native = createNativeRequest(bidRequest); imps.push(imp); @@ -521,15 +521,15 @@ export const spec = { const {id, img, data, title} = asset; const key = NATIVE_ID_MAP[id]; if (key) { - if (!utils.isEmpty(title)) { + if (!isEmpty(title)) { result.title = title.text - } else if (!utils.isEmpty(img)) { + } else if (!isEmpty(img)) { result[key] = { url: img.url, height: img.h, width: img.w } - } else if (!utils.isEmpty(data)) { + } else if (!isEmpty(data)) { result[key] = data.value; } } @@ -539,11 +539,11 @@ export const spec = { } let bids = []; - let resBids = utils.deepAccess(rtbResponse, 'body.seatbid') || []; + let resBids = deepAccess(rtbResponse, 'body.seatbid') || []; resBids.forEach(bid => { let resultItem = {requestId: bid.id, cpm: bid.price, creativeId: bid.crid, currency: bid.currency || 'USD', netRevenue: true, ttl: bid.ttl || 360, meta: {advertiserDomains: bid.adomain}}; - let mediaType = utils.deepAccess(bid, 'ext.mtype') || ''; + let mediaType = deepAccess(bid, 'ext.mtype') || ''; switch (mediaType) { case 'banner': bids.push(Object.assign({}, resultItem, {mediaType: BANNER, width: bid.w, height: bid.h, ad: bid.adm})); diff --git a/modules/deepintentBidAdapter.js b/modules/deepintentBidAdapter.js index 25c6ee9b25b..f2314454ab9 100644 --- a/modules/deepintentBidAdapter.js +++ b/modules/deepintentBidAdapter.js @@ -1,6 +1,6 @@ +import { generateUUID, deepSetValue, deepAccess, isArray } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER} from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'deepintent'; const BIDDER_ENDPOINT = 'https://prebid.deepintent.com/prebid'; const USER_SYNC_URL = 'https://cdn.deepintent.com/syncpixel.html'; @@ -32,7 +32,7 @@ export const spec = { var user = validBidRequests.map(bid => buildUser(bid)); clean(user); const openRtbBidRequest = { - id: utils.generateUUID(), + id: generateUUID(), at: 1, imp: validBidRequests.map(bid => buildImpression(bid)), site: buildSite(bidderRequest), @@ -41,12 +41,12 @@ export const spec = { }; if (bidderRequest && bidderRequest.uspConsent) { - utils.deepSetValue(openRtbBidRequest, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(openRtbBidRequest, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(openRtbBidRequest, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(openRtbBidRequest, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); + deepSetValue(openRtbBidRequest, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(openRtbBidRequest, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); } injectEids(openRtbBidRequest, validBidRequests); @@ -134,19 +134,19 @@ function buildUser(bid) { } function injectEids(openRtbBidRequest, validBidRequests) { - const bidUserIdAsEids = utils.deepAccess(validBidRequests, '0.userIdAsEids'); - if (utils.isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { - utils.deepSetValue(openRtbBidRequest, 'user.eids', bidUserIdAsEids); - utils.deepSetValue(openRtbBidRequest, 'user.ext.eids', bidUserIdAsEids); + const bidUserIdAsEids = deepAccess(validBidRequests, '0.userIdAsEids'); + if (isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { + deepSetValue(openRtbBidRequest, 'user.eids', bidUserIdAsEids); + deepSetValue(openRtbBidRequest, 'user.ext.eids', bidUserIdAsEids); } } function buildBanner(bid) { - if (utils.deepAccess(bid, 'mediaTypes.banner')) { + if (deepAccess(bid, 'mediaTypes.banner')) { // Get Sizes from MediaTypes Object, Will always take first size, will be overrided by params for exact w,h - if (utils.deepAccess(bid, 'mediaTypes.banner.sizes') && !bid.params.height && !bid.params.width) { - let sizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); - if (utils.isArray(sizes) && sizes.length > 0) { + if (deepAccess(bid, 'mediaTypes.banner.sizes') && !bid.params.height && !bid.params.width) { + let sizes = deepAccess(bid, 'mediaTypes.banner.sizes'); + if (isArray(sizes) && sizes.length > 0) { return { h: sizes[0][1], w: sizes[0][0], diff --git a/modules/dgkeywordRtdProvider.js b/modules/dgkeywordRtdProvider.js index 58cec36a6b9..a086091d464 100644 --- a/modules/dgkeywordRtdProvider.js +++ b/modules/dgkeywordRtdProvider.js @@ -7,7 +7,7 @@ * @requires module:modules/realTimeData */ -import * as utils from '../src/utils.js'; +import { logMessage, deepSetValue, logError, logInfo } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getGlobal } from '../src/prebidGlobal.js'; @@ -26,19 +26,19 @@ export function getDgKeywordsAndSet(reqBidsConfigObj, callback, moduleConfig, us const url = (moduleConfig && moduleConfig.params && moduleConfig.params.url) ? moduleConfig.params.url : URL + encodeURIComponent(window.location.href); const adUnits = reqBidsConfigObj.adUnits || getGlobal().adUnits; let isFinish = false; - utils.logMessage('[dgkeyword sub module]', adUnits, timeout); + logMessage('[dgkeyword sub module]', adUnits, timeout); let setKeywordTargetBidders = getTargetBidderOfDgKeywords(adUnits); if (setKeywordTargetBidders.length <= 0) { - utils.logMessage('[dgkeyword sub module] no dgkeyword targets.'); + logMessage('[dgkeyword sub module] no dgkeyword targets.'); callback(); } else { - utils.logMessage('[dgkeyword sub module] dgkeyword targets:', setKeywordTargetBidders); - utils.logMessage('[dgkeyword sub module] get targets from profile api start.'); + logMessage('[dgkeyword sub module] dgkeyword targets:', setKeywordTargetBidders); + logMessage('[dgkeyword sub module] get targets from profile api start.'); ajax(url, { success: function(response) { const res = JSON.parse(response); if (!isFinish) { - utils.logMessage('[dgkeyword sub module] get targets from profile api end.'); + logMessage('[dgkeyword sub module] get targets from profile api end.'); if (res) { let keywords = {}; if (res['s'] != null && res['s'].length > 0) { @@ -60,8 +60,8 @@ export function getDgKeywordsAndSet(reqBidsConfigObj, callback, moduleConfig, us if (!reqBidsConfigObj._ignoreSetOrtb2) { // set keywrods to ortb2 let addOrtb2 = {}; - utils.deepSetValue(addOrtb2, 'site.keywords', keywords); - utils.deepSetValue(addOrtb2, 'user.keywords', keywords); + deepSetValue(addOrtb2, 'site.keywords', keywords); + deepSetValue(addOrtb2, 'user.keywords', keywords); const ortb2 = {ortb2: addOrtb2}; reqBidsConfigObj.setBidderConfig({ bidders: Object.keys(targetBidKeys), config: ortb2 }); } @@ -73,7 +73,7 @@ export function getDgKeywordsAndSet(reqBidsConfigObj, callback, moduleConfig, us }, error: function(errorStatus) { // error occur - utils.logError('[dgkeyword sub module] profile api access error.', errorStatus); + logError('[dgkeyword sub module] profile api access error.', errorStatus); callback(); } }, null, { @@ -83,7 +83,7 @@ export function getDgKeywordsAndSet(reqBidsConfigObj, callback, moduleConfig, us setTimeout(function () { if (!isFinish) { // profile api timeout - utils.logInfo('[dgkeyword sub module] profile api timeout. [timeout: ' + timeout + 'ms]'); + logInfo('[dgkeyword sub module] profile api timeout. [timeout: ' + timeout + 'ms]'); isFinish = true; } callback(); diff --git a/modules/districtmDMXBidAdapter.js b/modules/districtmDMXBidAdapter.js index a35965c4cb4..f909a1f1329 100644 --- a/modules/districtmDMXBidAdapter.js +++ b/modules/districtmDMXBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isArray, generateUUID, deepAccess, isStr } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -30,7 +30,7 @@ export const spec = { interpretResponse(response, bidRequest) { response = response.body || {}; if (response.seatbid) { - if (utils.isArray(response.seatbid)) { + if (isArray(response.seatbid)) { const { seatbid } = response; let winners = seatbid.reduce((bid, ads) => { let ad = ads.bid.reduce(function (oBid, nBid) { @@ -89,7 +89,7 @@ export const spec = { let timeout = config.getConfig('bidderTimeout'); let schain = null; let dmxRequest = { - id: utils.generateUUID(), + id: generateUUID(), cur: ['USD'], tmax: (timeout - 300), test: this.test() || 0, @@ -109,17 +109,17 @@ export const spec = { let eids = []; if (bidRequest[0] && bidRequest[0].userId) { - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.idl_env`), 'liveramp.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.id5id.uid`), 'id5-sync.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.pubcid`), 'pubcid.org', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.tdid`), 'adserver.org', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.criteoId`), 'criteo.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.britepoolid`), 'britepool.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.lipb.lipbid`), 'liveintent.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.intentiqid`), 'intentiq.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.lotamePanoramaId`), 'lotame.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.parrableId`), 'parrable.com', 1); - bindUserId(eids, utils.deepAccess(bidRequest[0], `userId.netId`), 'netid.de', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.idl_env`), 'liveramp.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.id5id.uid`), 'id5-sync.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.pubcid`), 'pubcid.org', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.tdid`), 'adserver.org', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.criteoId`), 'criteo.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.britepoolid`), 'britepool.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.lipb.lipbid`), 'liveintent.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.intentiqid`), 'intentiq.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.lotamePanoramaId`), 'lotame.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.parrableId`), 'parrable.com', 1); + bindUserId(eids, deepAccess(bidRequest[0], `userId.netId`), 'netid.de', 1); dmxRequest.user = dmxRequest.user || {}; dmxRequest.user.ext = dmxRequest.user.ext || {}; dmxRequest.user.ext.eids = eids; @@ -370,7 +370,7 @@ export function defaultSize(thebidObj) { } export function bindUserId(eids, value, source, atype) { - if (utils.isStr(value) && Array.isArray(eids)) { + if (isStr(value) && Array.isArray(eids)) { eids.push({ source, uids: [ diff --git a/modules/dmdIdSystem.js b/modules/dmdIdSystem.js index 72d3518c20f..b42315d66ee 100644 --- a/modules/dmdIdSystem.js +++ b/modules/dmdIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; +import { logError, getWindowLocation } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { ajax } from '../src/ajax.js'; @@ -46,7 +46,7 @@ export const dmdIdSubmodule = { !configParams.api_key || typeof configParams.api_key !== 'string' ) { - utils.logError('dmd submodule requires an api_key.'); + logError('dmd submodule requires an api_key.'); return; } // If cahceIdObj is null or undefined - calling AIX-API @@ -59,7 +59,7 @@ export const dmdIdSubmodule = { // Setting headers const headers = {}; headers['x-api-key'] = configParams.api_key; - headers['x-domain'] = utils.getWindowLocation(); + headers['x-domain'] = getWindowLocation(); // Response callbacks const resp = function (callback) { const callbacks = { @@ -72,12 +72,12 @@ export const dmdIdSubmodule = { responseId = responseObj.dgid; } } catch (error) { - utils.logError(error); + logError(error); } callback(responseId); }, error: error => { - utils.logError(`${MODULE_NAME}: ID fetch encountered an error`, error); + logError(`${MODULE_NAME}: ID fetch encountered an error`, error); callback(); } }; diff --git a/modules/docereeBidAdapter.js b/modules/docereeBidAdapter.js index f9f3e1bcc70..704619f3ff7 100644 --- a/modules/docereeBidAdapter.js +++ b/modules/docereeBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { tryAppendQueryString } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER } from '../src/mediaTypes.js'; @@ -24,14 +24,14 @@ export const spec = { const { publisherUrl, placementId } = validBidRequest.params; const url = publisherUrl || page let queryString = ''; - queryString = utils.tryAppendQueryString(queryString, 'id', placementId); - queryString = utils.tryAppendQueryString(queryString, 'publisherDomain', domain); - queryString = utils.tryAppendQueryString(queryString, 'pubRequestedURL', encodeURIComponent(url)); - queryString = utils.tryAppendQueryString(queryString, 'loggedInUser', encodedUserInfo); - queryString = utils.tryAppendQueryString(queryString, 'currentUrl', url); - queryString = utils.tryAppendQueryString(queryString, 'prebidjs', true); - queryString = utils.tryAppendQueryString(queryString, 'token', token); - queryString = utils.tryAppendQueryString(queryString, 'requestId', validBidRequest.bidId); + queryString = tryAppendQueryString(queryString, 'id', placementId); + queryString = tryAppendQueryString(queryString, 'publisherDomain', domain); + queryString = tryAppendQueryString(queryString, 'pubRequestedURL', encodeURIComponent(url)); + queryString = tryAppendQueryString(queryString, 'loggedInUser', encodedUserInfo); + queryString = tryAppendQueryString(queryString, 'currentUrl', url); + queryString = tryAppendQueryString(queryString, 'prebidjs', true); + queryString = tryAppendQueryString(queryString, 'token', token); + queryString = tryAppendQueryString(queryString, 'requestId', validBidRequest.bidId); serverRequests.push({ method: 'GET', diff --git a/modules/dspxBidAdapter.js b/modules/dspxBidAdapter.js index df0f6f3b8ea..16c06073c41 100644 --- a/modules/dspxBidAdapter.js +++ b/modules/dspxBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -199,7 +199,7 @@ function objectToQueryString(obj, prefix) { * @returns {boolean} True if it's a banner bid */ function isBannerRequest(bid) { - return bid.mediaType === 'banner' || !!utils.deepAccess(bid, 'mediaTypes.banner') || !isVideoRequest(bid); + return bid.mediaType === 'banner' || !!deepAccess(bid, 'mediaTypes.banner') || !isVideoRequest(bid); } /** @@ -209,7 +209,7 @@ function isBannerRequest(bid) { * @returns {boolean} True if it's a video bid */ function isVideoRequest(bid) { - return bid.mediaType === 'video' || !!utils.deepAccess(bid, 'mediaTypes.video'); + return bid.mediaType === 'video' || !!deepAccess(bid, 'mediaTypes.video'); } /** @@ -219,7 +219,7 @@ function isVideoRequest(bid) { * @returns {object} True if it's a video bid */ function getVideoSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.video.playerSize') || bid.sizes); } /** @@ -229,7 +229,7 @@ function getVideoSizes(bid) { * @returns {object} True if it's a video bid */ function getBannerSizes(bid) { - return parseSizes(utils.deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); + return parseSizes(deepAccess(bid, 'mediaTypes.banner.sizes') || bid.sizes); } /** diff --git a/modules/ebdrBidAdapter.js b/modules/ebdrBidAdapter.js index cfbbbee61cb..62a3b171b74 100644 --- a/modules/ebdrBidAdapter.js +++ b/modules/ebdrBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logInfo, getBidIdParameter } from '../src/utils.js'; import { VIDEO, BANNER } from '../src/mediaTypes.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'ebdr'; @@ -18,11 +18,11 @@ export const spec = { let zoneid = ''; let requestId = ''; bids.forEach(bid => { - utils.logInfo('Log bid', bid); - let bidFloor = utils.getBidIdParameter('bidfloor', bid.params); + logInfo('Log bid', bid); + let bidFloor = getBidIdParameter('bidfloor', bid.params); let whArr = getWidthAndHeight(bid); let _mediaTypes = (bid.mediaTypes && bid.mediaTypes.video) ? VIDEO : BANNER; - zoneid = utils.getBidIdParameter('zoneid', bid.params); + zoneid = getBidIdParameter('zoneid', bid.params); requestId = bid.bidderRequestId; ebdrImps.push({ id: bid.bidId, @@ -36,9 +36,9 @@ export const spec = { w: whArr[0], h: whArr[1] }; - ebdrParams['latitude'] = utils.getBidIdParameter('latitude', bid.params); - ebdrParams['longitude'] = utils.getBidIdParameter('longitude', bid.params); - ebdrParams['ifa'] = (utils.getBidIdParameter('IDFA', bid.params).length > utils.getBidIdParameter('ADID', bid.params).length) ? utils.getBidIdParameter('IDFA', bid.params) : utils.getBidIdParameter('ADID', bid.params); + ebdrParams['latitude'] = getBidIdParameter('latitude', bid.params); + ebdrParams['longitude'] = getBidIdParameter('longitude', bid.params); + ebdrParams['ifa'] = (getBidIdParameter('IDFA', bid.params).length > getBidIdParameter('ADID', bid.params).length) ? getBidIdParameter('IDFA', bid.params) : getBidIdParameter('ADID', bid.params); }); let ebdrBidReq = { id: requestId, @@ -62,8 +62,8 @@ export const spec = { }; }, interpretResponse: function(serverResponse, bidRequest) { - utils.logInfo('Log serverResponse', serverResponse); - utils.logInfo('Log bidRequest', bidRequest); + logInfo('Log serverResponse', serverResponse); + logInfo('Log bidRequest', bidRequest); let ebdrResponseImps = []; const ebdrResponseObj = serverResponse.body; if (!ebdrResponseObj || !ebdrResponseObj.seatbid || ebdrResponseObj.seatbid.length === 0 || !ebdrResponseObj.seatbid[0].bid || ebdrResponseObj.seatbid[0].bid.length === 0) { diff --git a/modules/emx_digitalBidAdapter.js b/modules/emx_digitalBidAdapter.js index 260ffe105f4..3ab9af8e523 100644 --- a/modules/emx_digitalBidAdapter.js +++ b/modules/emx_digitalBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isArray, logWarn, logError, parseUrl, deepAccess, isStr, _each, getBidIdParameter, isFn, isPlainObject } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { Renderer } from '../src/Renderer.js'; @@ -18,11 +18,11 @@ const EIDS_SUPPORTED = [ export const emxAdapter = { validateSizes: (sizes) => { - if (!utils.isArray(sizes) || typeof sizes[0] === 'undefined') { - utils.logWarn(BIDDER_CODE + ': Sizes should be an array'); + if (!isArray(sizes) || typeof sizes[0] === 'undefined') { + logWarn(BIDDER_CODE + ': Sizes should be an array'); return false; } - return sizes.every(size => utils.isArray(size) && size.length === 2); + return sizes.every(size => isArray(size) && size.length === 2); }, checkVideoContext: (bid) => { return ((bid && bid.mediaTypes && bid.mediaTypes.video && bid.mediaTypes.video.context) && ((bid.mediaTypes.video.context === 'instream') || (bid.mediaTypes.video.context === 'outstream'))); @@ -31,7 +31,7 @@ export const emxAdapter = { let sizes = []; bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes ? sizes = bid.mediaTypes.banner.sizes : sizes = bid.sizes; if (!emxAdapter.validateSizes(sizes)) { - utils.logWarn(BIDDER_CODE + ': could not detect mediaType banner sizes. Assigning to bid sizes instead'); + logWarn(BIDDER_CODE + ': could not detect mediaType banner sizes. Assigning to bid sizes instead'); sizes = bid.sizes } return { @@ -78,7 +78,7 @@ export const emxAdapter = { cleanProtocols: (video) => { if (video.protocols && includes(video.protocols, 7)) { // not supporting VAST protocol 7 (VAST 4.0); - utils.logWarn(BIDDER_CODE + ': VAST 4.0 is currently not supported. This protocol has been filtered out of the request.'); + logWarn(BIDDER_CODE + ': VAST 4.0 is currently not supported. This protocol has been filtered out of the request.'); video.protocols = video.protocols.filter(protocol => protocol !== 7); } return video; @@ -106,7 +106,7 @@ export const emxAdapter = { try { renderer.setRender(emxAdapter.outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; @@ -114,7 +114,7 @@ export const emxAdapter = { buildVideo: (bid) => { let videoObj = Object.assign(bid.mediaTypes.video, bid.params.video); - if (utils.isArray(bid.mediaTypes.video.playerSize[0])) { + if (isArray(bid.mediaTypes.video.playerSize[0])) { videoObj['w'] = bid.mediaTypes.video.playerSize[0][0]; videoObj['h'] = bid.mediaTypes.video.playerSize[0][1]; } else { @@ -127,7 +127,7 @@ export const emxAdapter = { try { return decodeURIComponent(bidResponseAdm.replace(/%(?![0-9][0-9a-fA-F]+)/g, '%25')); } catch (err) { - utils.logError('emx_digitalBidAdapter', 'error', err); + logError('emx_digitalBidAdapter', 'error', err); } }, getReferrer: () => { @@ -138,7 +138,7 @@ export const emxAdapter = { } }, getSite: (refInfo) => { - let url = utils.parseUrl(refInfo.referer); + let url = parseUrl(refInfo.referer); return { domain: url.hostname, page: refInfo.referer, @@ -182,7 +182,7 @@ export const emxAdapter = { }, getUserId(bidRequests) { return ({ key, source, rtiPartner }) => { - let id = utils.deepAccess(bidRequests, `userId.${key}`); + let id = deepAccess(bidRequests, `userId.${key}`); return id ? emxAdapter.formatEid(id, source, rtiPartner) : null; }; }, @@ -203,17 +203,17 @@ export const spec = { supportedMediaTypes: [BANNER, VIDEO], isBidRequestValid: function (bid) { if (!bid || !bid.params) { - utils.logWarn(BIDDER_CODE + ': Missing bid or bid params.'); + logWarn(BIDDER_CODE + ': Missing bid or bid params.'); return false; } if (bid.bidder !== BIDDER_CODE) { - utils.logWarn(BIDDER_CODE + ': Must use "emx_digital" as bidder code.'); + logWarn(BIDDER_CODE + ': Must use "emx_digital" as bidder code.'); return false; } - if (!bid.params.tagid || !utils.isStr(bid.params.tagid)) { - utils.logWarn(BIDDER_CODE + ': Missing tagid param or tagid present and not type String.'); + if (!bid.params.tagid || !isStr(bid.params.tagid)) { + logWarn(BIDDER_CODE + ': Missing tagid param or tagid present and not type String.'); return false; } @@ -221,17 +221,17 @@ export const spec = { let sizes; bid.mediaTypes.banner.sizes ? sizes = bid.mediaTypes.banner.sizes : sizes = bid.sizes; if (!emxAdapter.validateSizes(sizes)) { - utils.logWarn(BIDDER_CODE + ': Missing sizes in bid'); + logWarn(BIDDER_CODE + ': Missing sizes in bid'); return false; } } else if (bid.mediaTypes && bid.mediaTypes.video) { if (!emxAdapter.checkVideoContext(bid)) { - utils.logWarn(BIDDER_CODE + ': Missing video context: instream or outstream'); + logWarn(BIDDER_CODE + ': Missing video context: instream or outstream'); return false; } if (!bid.mediaTypes.video.playerSize) { - utils.logWarn(BIDDER_CODE + ': Missing video playerSize'); + logWarn(BIDDER_CODE + ': Missing video playerSize'); return false; } } @@ -247,8 +247,8 @@ export const spec = { const device = emxAdapter.getDevice(); const site = emxAdapter.getSite(bidderRequest.refererInfo); - utils._each(validBidRequests, function (bid) { - let tagid = utils.getBidIdParameter('tagid', bid.params); + _each(validBidRequests, function (bid) { + let tagid = getBidIdParameter('tagid', bid.params); let bidfloor = parseFloat(getBidFloor(bid)) || 0; let isVideo = !!bid.mediaTypes.video; let data = { @@ -364,8 +364,8 @@ export const spec = { // support floors module in prebid 5.0 function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return parseFloat(utils.getBidIdParameter('bidfloor', bid.params)); + if (!isFn(bid.getFloor)) { + return parseFloat(getBidIdParameter('bidfloor', bid.params)); } let floor = bid.getFloor({ @@ -373,7 +373,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; diff --git a/modules/enrichmentFpdModule.js b/modules/enrichmentFpdModule.js index e1942fbadc3..9268c81c033 100644 --- a/modules/enrichmentFpdModule.js +++ b/modules/enrichmentFpdModule.js @@ -1,8 +1,9 @@ + /** * This module sets default values and validates ortb2 first part data * @module modules/firstPartyData */ -import * as utils from '../src/utils.js'; +import { timestamp, mergeDeep } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { getRefererInfo } from '../src/refererDetection.js'; import { getCoreStorageManager } from '../src/storageManager.js'; @@ -32,7 +33,7 @@ export function findRootDomain(fullDomain = window.location.hostname) { const TEST_COOKIE_VALUE = 'writeable'; do { rootDomain = domainParts.slice(startIndex).join('.'); - let expirationDate = new Date(utils.timestamp() + 10 * 1000).toUTCString(); + let expirationDate = new Date(timestamp() + 10 * 1000).toUTCString(); // Write a test cookie coreStorage.setCookie( @@ -69,14 +70,14 @@ export function findRootDomain(fullDomain = window.location.hostname) { * Checks for referer and if exists merges into ortb2 global data */ function setReferer() { - if (getRefererInfo().referer) utils.mergeDeep(ortb2, { site: { ref: getRefererInfo().referer } }); + if (getRefererInfo().referer) mergeDeep(ortb2, { site: { ref: getRefererInfo().referer } }); } /** * Checks for canonical url and if exists merges into ortb2 global data */ function setPage() { - if (getRefererInfo().canonicalUrl) utils.mergeDeep(ortb2, { site: { page: getRefererInfo().canonicalUrl } }); + if (getRefererInfo().canonicalUrl) mergeDeep(ortb2, { site: { page: getRefererInfo().canonicalUrl } }); } /** @@ -94,8 +95,8 @@ function setDomain() { let domain = parseDomain(getRefererInfo().canonicalUrl) if (domain) { - utils.mergeDeep(ortb2, { site: { domain: domain } }); - utils.mergeDeep(ortb2, { site: { publisher: { domain: findRootDomain(domain) } } }); + mergeDeep(ortb2, { site: { domain: domain } }); + mergeDeep(ortb2, { site: { publisher: { domain: findRootDomain(domain) } } }); }; } @@ -114,7 +115,7 @@ function setDimensions() { height = window.innerHeight || window.document.documentElement.clientHeight || window.document.body.clientHeight; } - utils.mergeDeep(ortb2, { device: { w: width, h: height } }); + mergeDeep(ortb2, { device: { w: width, h: height } }); } /** @@ -129,7 +130,7 @@ function setKeywords() { keywords = window.document.querySelector("meta[name='keywords']"); } - if (keywords && keywords.content) utils.mergeDeep(ortb2, { site: { keywords: keywords.content.replace(/\s/g, '') } }); + if (keywords && keywords.content) mergeDeep(ortb2, { site: { keywords: keywords.content.replace(/\s/g, '') } }); } /** @@ -153,7 +154,7 @@ function runEnrichments() { export function initSubmodule(fpdConf, data) { resetOrtb2(); - return (!fpdConf.skipEnrichments) ? utils.mergeDeep(runEnrichments(), data) : data; + return (!fpdConf.skipEnrichments) ? mergeDeep(runEnrichments(), data) : data; } /** @type {firstPartyDataSubmodule} */ diff --git a/modules/eplanningAnalyticsAdapter.js b/modules/eplanningAnalyticsAdapter.js index 08db2f2ca9d..fb77014400c 100644 --- a/modules/eplanningAnalyticsAdapter.js +++ b/modules/eplanningAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { logError } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; const CONSTANTS = require('../src/constants.json'); @@ -110,7 +110,7 @@ eplAnalyticsAdapter.originEnableAnalytics = eplAnalyticsAdapter.enableAnalytics; eplAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.ci) { - utils.logError('Client ID (ci) option is not defined. Analytics won\'t work'); + logError('Client ID (ci) option is not defined. Analytics won\'t work'); return; } diff --git a/modules/eplanningBidAdapter.js b/modules/eplanningBidAdapter.js index dd96353dea3..5aef90d413d 100644 --- a/modules/eplanningBidAdapter.js +++ b/modules/eplanningBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isEmpty, getWindowSelf, parseSizesInput } from '../src/utils.js'; import { getGlobal } from '../src/prebidGlobal.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -102,9 +102,9 @@ export const spec = { const response = serverResponse.body; let bidResponses = []; - if (response && !utils.isEmpty(response.sp)) { + if (response && !isEmpty(response.sp)) { response.sp.forEach(space => { - if (!utils.isEmpty(space.a)) { + if (!isEmpty(space.a)) { space.a.forEach(ad => { const bidResponse = { requestId: request.adUnitToBidId[space.k], @@ -132,9 +132,9 @@ export const spec = { }, getUserSyncs: function(syncOptions, serverResponses) { const syncs = []; - const response = !utils.isEmpty(serverResponses) && serverResponses[0].body; + const response = !isEmpty(serverResponses) && serverResponses[0].body; - if (response && !utils.isEmpty(response.cs)) { + if (response && !isEmpty(response.cs)) { const responseSyncs = response.cs; responseSyncs.forEach(sync => { if (typeof sync === 'string' && syncOptions.pixelEnabled) { @@ -159,7 +159,7 @@ function getUserAgent() { return window.navigator.userAgent; } function getInnerWidth() { - return utils.getWindowSelf().innerWidth; + return getWindowSelf().innerWidth; } function isMobileUserAgent() { return getUserAgent().match(/(mobile)|(ip(hone|ad))|(android)|(blackberry)|(nokia)|(phone)|(opera\smini)/i); @@ -216,7 +216,7 @@ function compareSizesByPriority(size1, size2) { } function getSizesSortedByPriority(sizes) { - return utils.parseSizesInput(sizes).sort(compareSizesByPriority); + return parseSizesInput(sizes).sort(compareSizesByPriority); } function getSize(bid, first) { diff --git a/modules/etargetBidAdapter.js b/modules/etargetBidAdapter.js index 51f2759d256..f7d552b1b09 100644 --- a/modules/etargetBidAdapter.js +++ b/modules/etargetBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepSetValue, isFn, isPlainObject } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -145,7 +145,7 @@ export const spec = { bidObject.gdpr_consent = bidRequest.gdpr.gdpr_consent; } if (bid.adomain) { - utils.deepSetValue(bidObject, 'meta.advertiserDomains', Array.isArray(bid.adomain) ? bid.adomain : [bid.adomain]); + deepSetValue(bidObject, 'meta.advertiserDomains', Array.isArray(bid.adomain) ? bid.adomain : [bid.adomain]); } bidRespones.push(bidObject); } @@ -165,7 +165,7 @@ export const spec = { } }; function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return null; } let floor = bid.getFloor({ @@ -173,7 +173,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor)) { + if (isPlainObject(floor) && !isNaN(floor.floor)) { return floor.floor; } return null; diff --git a/modules/express.js b/modules/express.js index f4a76daefdf..0b1780e3c26 100644 --- a/modules/express.js +++ b/modules/express.js @@ -1,5 +1,4 @@ - -import * as utils from '../src/utils.js'; +import { logMessage, logWarn, logError, logInfo } from '../src/utils.js'; const MODULE_NAME = 'express'; @@ -14,10 +13,10 @@ const MODULE_NAME = 'express'; * @param {Object[]} [adUnits = pbjs.adUnits] - an array of adUnits for express to operate on. */ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { - utils.logMessage('loading ' + MODULE_NAME); + logMessage('loading ' + MODULE_NAME); if (adUnits.length === 0) { - utils.logWarn('no valid adUnits found, not loading ' + MODULE_NAME); + logWarn('no valid adUnits found, not loading ' + MODULE_NAME); } // store gpt slots in a more performant hash lookup by elementId (adUnit code) @@ -27,7 +26,7 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { if (adUnit.code && adUnit.bids) { cache[adUnit.code] = adUnit; } else { - utils.logError('misconfigured adUnit', null, adUnit); + logError('misconfigured adUnit', null, adUnit); } return cache; }, {}); @@ -39,10 +38,10 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { var gpt = window.googletag; var pads = gpt.pubads; if (!gpt.display || !gpt.enableServices || typeof pads !== 'function' || !pads().refresh || !pads().disableInitialLoad || !pads().getSlots || !pads().enableSingleRequest) { - utils.logError('could not bind to gpt googletag api'); + logError('could not bind to gpt googletag api'); return; } - utils.logMessage('running'); + logMessage('running'); // function to convert google tag slot sizes to [[w,h],...] function mapGptSlotSizes(aGPTSlotSizes) { @@ -51,7 +50,7 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { try { aSlotSizes.push([aGPTSlotSizes[i].getWidth(), aGPTSlotSizes[i].getHeight()]); } catch (e) { - utils.logWarn('slot size ' + aGPTSlotSizes[i].toString() + ' not supported by' + MODULE_NAME); + logWarn('slot size ' + aGPTSlotSizes[i].toString() + ' not supported by' + MODULE_NAME); } } return aSlotSizes; @@ -110,7 +109,7 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { // - else run an auction and call the real fGptRefresh() to // initiate the DFP request gpt.display = function (sElementId) { - utils.logInfo('display:', sElementId); + logInfo('display:', sElementId); // call original gpt display() function fGptDisplay.apply(gpt, arguments); @@ -157,7 +156,7 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { // override gpt refresh() function // - run auctions for provided gpt slots, then initiate ad-server call pads().refresh = function (aGptSlots, options) { - utils.logInfo('refresh:', aGptSlots); + logInfo('refresh:', aGptSlots); // get already displayed adUnits from aGptSlots if provided, else all defined gptSlots aGptSlots = defaultSlots(aGptSlots); var adUnits = pickAdUnits(/* mutated: */ aGptSlots).filter(function (adUnit) { diff --git a/modules/fabrickIdSystem.js b/modules/fabrickIdSystem.js index bb838788f07..08eb2d4f043 100644 --- a/modules/fabrickIdSystem.js +++ b/modules/fabrickIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logError } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getRefererInfo } from '../src/refererDetection.js'; @@ -47,7 +47,7 @@ export const fabrickIdSubmodule = { window.fabrickMod1(configParams, consentData, cacheIdObj); } if (!configParams || !configParams.apiKey || typeof configParams.apiKey !== 'string') { - utils.logError('fabrick submodule requires an apiKey.'); + logError('fabrick submodule requires an apiKey.'); return; } try { @@ -96,7 +96,7 @@ export const fabrickIdSubmodule = { try { responseObj = JSON.parse(response); } catch (error) { - utils.logError(error); + logError(error); responseObj = {}; } } @@ -104,7 +104,7 @@ export const fabrickIdSubmodule = { } }, error: error => { - utils.logError(`fabrickId fetch encountered an error`, error); + logError(`fabrickId fetch encountered an error`, error); callback(); } }; @@ -112,10 +112,10 @@ export const fabrickIdSubmodule = { }; return {callback: resp}; } catch (e) { - utils.logError(`fabrickIdSystem encountered an error`, e); + logError(`fabrickIdSystem encountered an error`, e); } } catch (e) { - utils.logError(`fabrickIdSystem encountered an error`, e); + logError(`fabrickIdSystem encountered an error`, e); } } }; From 467ad51691654fbfd5b3cee5ac8cf1a841e48940 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 11:54:46 -0700 Subject: [PATCH 29/84] Pbjs Core: avoid import all from utils in src/ files (#7466) * adloader: not importing * from utils * ajax: not importing * from utils * AnalyticsAdapter: not importing * from utils * adapterManager: not importing * from utils * auction: not importing * from utils * bidfactory: not importing * from utils * config: not importing * from utils * cpmBucketManager: not importing * from utils * prebid: not importing * from utils * Renderer: not importing * from utils * storageManager: not importing * from utils * targeting: not importing * from utils * userSync: not importing * from utils * videoCache: not importing * from utils --- src/AnalyticsAdapter.js | 12 +-- src/Renderer.js | 18 +++-- src/adapterManager.js | 87 +++++++++++---------- src/adloader.js | 12 +-- src/ajax.js | 17 ++-- src/auction.js | 49 ++++++------ src/bidfactory.js | 4 +- src/config.js | 102 ++++++++++++------------ src/cpmBucketManager.js | 4 +- src/prebid.js | 166 ++++++++++++++++++++-------------------- src/storageManager.js | 10 +-- src/targeting.js | 30 ++++---- src/userSync.js | 43 ++++++----- src/videoCache.js | 4 +- 14 files changed, 288 insertions(+), 270 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}`); } } 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 !!( 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); }; 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; } 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); } } 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); } } } 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; 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'); } } } 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; 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); } } }); 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(); diff --git a/src/targeting.js b/src/targeting.js index ce519f8add3..61a9f9a76b7 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)); }; @@ -388,7 +390,7 @@ export function newTargeting(auctionManager) { } targetingConfig[targetId][key] = value; }); - utils.logMessage(`Attempting to set targeting-map for slot: ${slot.getSlotElementId()} with targeting-map:`, targetingConfig[targetId]); + logMessage(`Attempting to set targeting-map for slot: ${slot.getSlotElementId()} with targeting-map:`, targetingConfig[targetId]); slot.updateTargetingFromMap(targetingConfig[targetId]) }) }) @@ -402,7 +404,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() || []; @@ -452,14 +454,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) { @@ -524,7 +526,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); @@ -631,8 +633,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] }; }); } @@ -645,7 +647,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; } }; diff --git a/src/userSync.js b/src/userSync.js index fc9f577fd7e..60e605f29fb 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) { // Image pixels fireImagePixels(); } 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); }); } @@ -141,9 +144,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); // for a bidder, if iframe sync is present then remove image pixel removeImagePixelsForBidder(queue, bidderName); }); @@ -187,21 +190,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 @@ -248,7 +251,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; } @@ -265,12 +268,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; } @@ -312,7 +315,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'), 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; } } From b815976146d912c533395c71a9e9679fc62ae536 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 11:55:13 -0700 Subject: [PATCH 30/84] Key Prebid Modules: import only what is needed from utils (#7468) * validationFPDModule: import only what is needed from utils * userIdModule: import only what is needed from utils * rtdModule: import only what is needed from utils * PBS: import only what is needed from utils * multibid: import only what is needed from utils --- modules/multibid/index.js | 28 ++-- modules/prebidServerBidAdapter/index.js | 212 ++++++++++++------------ modules/rtdModule/index.js | 6 +- modules/userId/eids.js | 18 +- modules/userId/index.js | 72 ++++---- modules/validationFpdModule/index.js | 30 ++-- 6 files changed, 187 insertions(+), 179 deletions(-) diff --git a/modules/multibid/index.js b/modules/multibid/index.js index dd4999b2dca..cf4821de183 100644 --- a/modules/multibid/index.js +++ b/modules/multibid/index.js @@ -5,7 +5,9 @@ import {config} from '../../src/config.js'; import {setupBeforeHookFnOnce, getHook} from '../../src/hook.js'; -import * as utils from '../../src/utils.js'; +import { + logWarn, deepAccess, getUniqueIdentifierStr, deepSetValue, groupBy +} from '../../src/utils.js'; import events from '../../src/events.js'; import CONSTANTS from '../../src/constants.json'; import {addBidderRequests} from '../../src/auction.js'; @@ -50,7 +52,7 @@ export function validateMultibid(conf) { let duplicate = conf.filter(entry => { // Check if entry.bidder is not defined or typeof string, filter entry and reset configuration if ((!entry.bidder || typeof entry.bidder !== 'string') && (!entry.bidders || !Array.isArray(entry.bidders))) { - utils.logWarn('Filtering multibid entry. Missing required bidder or bidders property.'); + logWarn('Filtering multibid entry. Missing required bidder or bidders property.'); check = false; return false; } @@ -97,26 +99,26 @@ export function adjustBidderRequestsHook(fn, bidderRequests) { * @param {Object} bid object */ export function addBidResponseHook(fn, adUnitCode, bid) { - let floor = utils.deepAccess(bid, 'floorData.floorValue'); + let floor = deepAccess(bid, 'floorData.floorValue'); if (!config.getConfig('multibid')) resetMultiConfig(); // Checks if multiconfig exists and bid bidderCode exists within config and is an adpod bid // Else checks if multiconfig exists and bid bidderCode exists within config // Else continue with no modifications - if (hasMultibid && multiConfig[bid.bidderCode] && utils.deepAccess(bid, 'video.context') === 'adpod') { + if (hasMultibid && multiConfig[bid.bidderCode] && deepAccess(bid, 'video.context') === 'adpod') { fn.call(this, adUnitCode, bid); } else if (hasMultibid && multiConfig[bid.bidderCode]) { // Set property multibidPrefix on bid if (multiConfig[bid.bidderCode].prefix) bid.multibidPrefix = multiConfig[bid.bidderCode].prefix; bid.originalBidder = bid.bidderCode; // Check if stored bids for auction include adUnitCode.bidder and max limit not reach for ad unit - if (utils.deepAccess(multibidUnits, `${adUnitCode}.${bid.bidderCode}`)) { + if (deepAccess(multibidUnits, `${adUnitCode}.${bid.bidderCode}`)) { // Store request id under new property originalRequestId, create new unique bidId, // and push bid into multibid stored bids for auction if max not reached and bid cpm above floor if (!multibidUnits[adUnitCode][bid.bidderCode].maxReached && (!floor || floor <= bid.cpm)) { bid.originalRequestId = bid.requestId; - bid.requestId = utils.getUniqueIdentifierStr(); + bid.requestId = getUniqueIdentifierStr(); multibidUnits[adUnitCode][bid.bidderCode].ads.push(bid); let length = multibidUnits[adUnitCode][bid.bidderCode].ads.length; @@ -126,12 +128,12 @@ export function addBidResponseHook(fn, adUnitCode, bid) { fn.call(this, adUnitCode, bid); } else { - utils.logWarn(`Filtering multibid received from bidder ${bid.bidderCode}: ` + ((multibidUnits[adUnitCode][bid.bidderCode].maxReached) ? `Maximum bid limit reached for ad unit code ${adUnitCode}` : 'Bid cpm under floors value.')); + logWarn(`Filtering multibid received from bidder ${bid.bidderCode}: ` + ((multibidUnits[adUnitCode][bid.bidderCode].maxReached) ? `Maximum bid limit reached for ad unit code ${adUnitCode}` : 'Bid cpm under floors value.')); } } else { - if (utils.deepAccess(bid, 'floorData.floorValue')) utils.deepSetValue(multibidUnits, `${adUnitCode}.${bid.bidderCode}`, {floor: utils.deepAccess(bid, 'floorData.floorValue')}); + if (deepAccess(bid, 'floorData.floorValue')) deepSetValue(multibidUnits, `${adUnitCode}.${bid.bidderCode}`, {floor: deepAccess(bid, 'floorData.floorValue')}); - utils.deepSetValue(multibidUnits, `${adUnitCode}.${bid.bidderCode}`, {ads: [bid]}); + deepSetValue(multibidUnits, `${adUnitCode}.${bid.bidderCode}`, {ads: [bid]}); if (multibidUnits[adUnitCode][bid.bidderCode].ads.length === multiConfig[bid.bidderCode].maxbids) multibidUnits[adUnitCode][bid.bidderCode].maxReached = true; fn.call(this, adUnitCode, bid); @@ -170,11 +172,11 @@ export function targetBidPoolHook(fn, bidsReceived, highestCpmCallback, adUnitBi if (hasMultibid) { const dealPrioritization = config.getConfig('sendBidsControl.dealPrioritization'); let modifiedBids = []; - let buckets = utils.groupBy(bidsReceived, 'adUnitCode'); + let buckets = groupBy(bidsReceived, 'adUnitCode'); let bids = [].concat.apply([], Object.keys(buckets).reduce((result, slotId) => { let bucketBids = []; // Get bids and group by property originalBidder - let bidsByBidderName = utils.groupBy(buckets[slotId], 'originalBidder'); + let bidsByBidderName = groupBy(buckets[slotId], 'originalBidder'); let adjustedBids = [].concat.apply([], Object.keys(bidsByBidderName).map(key => { // Reset all bidderCodes to original bidder values and sort by CPM return bidsByBidderName[key].sort((bidA, bidB) => { @@ -183,7 +185,7 @@ export function targetBidPoolHook(fn, bidsReceived, highestCpmCallback, adUnitBi return bidA.cpm > bidB.cpm ? -1 : (bidA.cpm < bidB.cpm ? 1 : 0); }).map((bid, index) => { // For each bid (post CPM sort), set dynamic bidderCode using prefix and index if less than maxbid amount - if (utils.deepAccess(multiConfig, `${bid.bidderCode}.prefix`) && index !== 0 && index < multiConfig[bid.bidderCode].maxbids) { + if (deepAccess(multiConfig, `${bid.bidderCode}.prefix`) && index !== 0 && index < multiConfig[bid.bidderCode].maxbids) { bid.bidderCode = multiConfig[bid.bidderCode].prefix + (index + 1); } @@ -191,7 +193,7 @@ export function targetBidPoolHook(fn, bidsReceived, highestCpmCallback, adUnitBi }) })); // Get adjustedBids by bidderCode and reduce using highestCpmCallback - let bidsByBidderCode = utils.groupBy(adjustedBids, 'bidderCode'); + let bidsByBidderCode = groupBy(adjustedBids, 'bidderCode'); Object.keys(bidsByBidderCode).forEach(key => bucketBids.push(bidsByBidderCode[key].reduce(highestCpmCallback))); // if adUnitBidLimit is set, pass top N number bids if (adUnitBidLimit > 0) { diff --git a/modules/prebidServerBidAdapter/index.js b/modules/prebidServerBidAdapter/index.js index d7caf0dbad8..245cb7fc0b0 100644 --- a/modules/prebidServerBidAdapter/index.js +++ b/modules/prebidServerBidAdapter/index.js @@ -1,6 +1,11 @@ import Adapter from '../../src/adapter.js'; import { createBid } from '../../src/bidfactory.js'; -import * as utils from '../../src/utils.js'; +import { + getPrebidInternal, logError, isStr, isPlainObject, logWarn, generateUUID, bind, logMessage, + triggerPixel, insertUserSyncIframe, deepAccess, mergeDeep, deepSetValue, cleanObj, parseSizesInput, + getBidRequest, getDefinedParams, createTrackPixelHtml, pick, deepClone, uniques, flatten, isNumber, + isEmpty, isArray, logInfo +} from '../../src/utils.js'; import CONSTANTS from '../../src/constants.json'; import adapterManager from '../../src/adapterManager.js'; import { config } from '../../src/config.js'; @@ -12,7 +17,6 @@ import includes from 'core-js-pure/features/array/includes.js'; import { S2S_VENDORS } from './config.js'; import { ajax } from '../../src/ajax.js'; import find from 'core-js-pure/features/array/find.js'; -import { getPrebidInternal } from '../../src/utils.js'; const getConfig = config.getConfig; @@ -100,7 +104,7 @@ function updateConfigDefaultVendor(option) { } }); } else { - utils.logError('Incorrect or unavailable prebid server default vendor option: ' + vendor); + logError('Incorrect or unavailable prebid server default vendor option: ' + vendor); return false; } } @@ -116,7 +120,7 @@ function validateConfigRequiredProps(option) { const keys = Object.keys(option); if (['accountId', 'bidders', 'endpoint'].filter(key => { if (!includes(keys, key)) { - utils.logError(key + ' missing in server to server config'); + logError(key + ' missing in server to server config'); return true; } return false; @@ -129,14 +133,14 @@ function validateConfigRequiredProps(option) { // could be removed later as part of a major release, if we decide to not support the old format function formatUrlParams(option) { ['endpoint', 'syncEndpoint'].forEach((prop) => { - if (utils.isStr(option[prop])) { + if (isStr(option[prop])) { let temp = option[prop]; option[prop] = { p1Consent: temp, noP1Consent: temp }; } - if (utils.isPlainObject(option[prop]) && (!option[prop].p1Consent || !option[prop].noP1Consent)) { + if (isPlainObject(option[prop]) && (!option[prop].p1Consent || !option[prop].noP1Consent)) { ['p1Consent', 'noP1Consent'].forEach((conUrl) => { if (!option[prop][conUrl]) { - utils.logWarn(`s2sConfig.${prop}.${conUrl} not defined. PBS request will be skipped in some P1 scenarios.`); + logWarn(`s2sConfig.${prop}.${conUrl} not defined. PBS request will be skipped in some P1 scenarios.`); } }); } @@ -171,7 +175,7 @@ function setS2sConfig(options) { return true; } } - utils.logWarn('prebidServer: s2s config is disabled'); + logWarn('prebidServer: s2s config is disabled'); return false; }); @@ -198,13 +202,13 @@ function queueSync(bidderCodes, gdprConsent, uspConsent, s2sConfig) { _syncCount++; const payload = { - uuid: utils.generateUUID(), + uuid: generateUUID(), bidders: bidderCodes, account: s2sConfig.accountId }; let userSyncLimit = s2sConfig.userSyncLimit; - if (utils.isNumber(userSyncLimit) && userSyncLimit > 0) { + if (isNumber(userSyncLimit) && userSyncLimit > 0) { payload['limit'] = userSyncLimit; } @@ -232,7 +236,7 @@ function queueSync(bidderCodes, gdprConsent, uspConsent, s2sConfig) { response = JSON.parse(response); doAllSyncs(response.bidder_status, s2sConfig); } catch (e) { - utils.logError(e); + logError(e); } }, jsonPayload, @@ -252,7 +256,7 @@ function doAllSyncs(bidders, s2sConfig) { // if PBS reports this bidder doesn't have an ID, then call the sync and recurse to the next sync entry if (thisSync.no_cookie) { - doPreBidderSync(thisSync.usersync.type, thisSync.usersync.url, thisSync.bidder, utils.bind.call(doAllSyncs, null, bidders, s2sConfig), s2sConfig); + doPreBidderSync(thisSync.usersync.type, thisSync.usersync.url, thisSync.bidder, bind.call(doAllSyncs, null, bidders, s2sConfig), s2sConfig); } else { // bidder already has an ID, so just recurse to the next sync entry doAllSyncs(bidders, s2sConfig); @@ -287,16 +291,16 @@ function doPreBidderSync(type, url, bidder, done, s2sConfig) { */ function doBidderSync(type, url, bidder, done) { if (!url) { - utils.logError(`No sync url for bidder "${bidder}": ${url}`); + logError(`No sync url for bidder "${bidder}": ${url}`); done(); } else if (type === 'image' || type === 'redirect') { - utils.logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`); - utils.triggerPixel(url, done); + logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`); + triggerPixel(url, done); } else if (type == 'iframe') { - utils.logMessage(`Invoking iframe user sync for bidder: "${bidder}"`); - utils.insertUserSyncIframe(url, done); + logMessage(`Invoking iframe user sync for bidder: "${bidder}"`); + insertUserSyncIframe(url, done); } else { - utils.logError(`User sync type "${type}" not supported for bidder: "${bidder}"`); + logError(`User sync type "${type}" not supported for bidder: "${bidder}"`); done(); } } @@ -312,7 +316,7 @@ function doClientSideSyncs(bidders, gdprConsent, uspConsent) { if (clientAdapter && clientAdapter.registerSyncs) { config.runWithBidder( bidder, - utils.bind.call( + bind.call( clientAdapter.registerSyncs, clientAdapter, [], @@ -333,12 +337,12 @@ function _appendSiteAppDevice(request, pageUrl, accountId) { request.app.publisher = {id: accountId} } else { request.site = {}; - if (utils.isPlainObject(config.getConfig('site'))) { + if (isPlainObject(config.getConfig('site'))) { request.site = config.getConfig('site'); } // set publisher.id if not already defined - if (!utils.deepAccess(request.site, 'publisher.id')) { - utils.deepSetValue(request.site, 'publisher.id', accountId); + if (!deepAccess(request.site, 'publisher.id')) { + deepSetValue(request.site, 'publisher.id', accountId); } // set site.page if not already defined if (!request.site.page) { @@ -364,7 +368,7 @@ function addBidderFirstPartyDataToRequest(request) { const fpdConfigs = Object.keys(bidderConfig).reduce((acc, bidder) => { const currBidderConfig = bidderConfig[bidder]; if (currBidderConfig.ortb2) { - const ortb2 = utils.mergeDeep({}, currBidderConfig.ortb2); + const ortb2 = mergeDeep({}, currBidderConfig.ortb2); acc.push({ bidders: [ bidder ], @@ -375,7 +379,7 @@ function addBidderFirstPartyDataToRequest(request) { }, []); if (fpdConfigs.length) { - utils.deepSetValue(request, 'ext.prebid.bidderconfig', fpdConfigs); + deepSetValue(request, 'ext.prebid.bidderconfig', fpdConfigs); } } @@ -442,13 +446,13 @@ let wurlMap = {}; * @param {string} wurl events.winurl passed from prebidServer as wurl */ function addWurl(auctionId, adId, wurl) { - if ([auctionId, adId].every(utils.isStr)) { + if ([auctionId, adId].every(isStr)) { wurlMap[`${auctionId}${adId}`] = wurl; } } function getPbsResponseData(bidderRequests, response, pbsName, pbjsName) { - const bidderValues = utils.deepAccess(response, `ext.${pbsName}`); + const bidderValues = deepAccess(response, `ext.${pbsName}`); if (bidderValues) { Object.keys(bidderValues).forEach(bidder => { let biddersReq = find(bidderRequests, bidderReq => bidderReq.bidderCode === bidder); @@ -464,7 +468,7 @@ function getPbsResponseData(bidderRequests, response, pbsName, pbjsName) { * @param {string} adId generated value set to bidObject.adId by bidderFactory Bid() */ function removeWurl(auctionId, adId) { - if ([auctionId, adId].every(utils.isStr)) { + if ([auctionId, adId].every(isStr)) { wurlMap[`${auctionId}${adId}`] = undefined; } } @@ -474,7 +478,7 @@ function removeWurl(auctionId, adId) { * @return {(string|undefined)} events.winurl which was passed as wurl */ function getWurl(auctionId, adId) { - if ([auctionId, adId].every(utils.isStr)) { + if ([auctionId, adId].every(isStr)) { return wurlMap[`${auctionId}${adId}`]; } } @@ -506,7 +510,7 @@ const OPEN_RTB_PROTOCOL = { } impIds.add(impressionId); - const nativeParams = processNativeAdUnitParams(utils.deepAccess(adUnit, 'mediaTypes.native')); + const nativeParams = processNativeAdUnitParams(deepAccess(adUnit, 'mediaTypes.native')); let nativeAssets; if (nativeParams) { try { @@ -516,19 +520,19 @@ const OPEN_RTB_PROTOCOL = { function newAsset(obj) { return Object.assign({ required: params.required ? 1 : 0 - }, obj ? utils.cleanObj(obj) : {}); + }, obj ? cleanObj(obj) : {}); } switch (type) { case 'image': case 'icon': let imgTypeId = nativeImgIdMap[type]; - let asset = utils.cleanObj({ + let asset = cleanObj({ type: imgTypeId, - w: utils.deepAccess(params, 'sizes.0'), - h: utils.deepAccess(params, 'sizes.1'), - wmin: utils.deepAccess(params, 'aspect_ratios.0.min_width'), - hmin: utils.deepAccess(params, 'aspect_ratios.0.min_height') + w: deepAccess(params, 'sizes.0'), + h: deepAccess(params, 'sizes.1'), + wmin: deepAccess(params, 'aspect_ratios.0.min_width'), + hmin: deepAccess(params, 'aspect_ratios.0.min_height') }); if (!((asset.w && asset.h) || (asset.hmin && asset.wmin))) { throw 'invalid img sizes (must provide sizes or min_height & min_width if using aspect_ratios)'; @@ -569,11 +573,11 @@ const OPEN_RTB_PROTOCOL = { return assets; }, []); } catch (e) { - utils.logError('error creating native request: ' + String(e)) + logError('error creating native request: ' + String(e)) } } - const videoParams = utils.deepAccess(adUnit, 'mediaTypes.video'); - const bannerParams = utils.deepAccess(adUnit, 'mediaTypes.banner'); + const videoParams = deepAccess(adUnit, 'mediaTypes.video'); + const bannerParams = deepAccess(adUnit, 'mediaTypes.banner'); adUnit.bids.forEach(bid => { // OpenRTB response contains imp.id and bidder name. These are @@ -592,7 +596,7 @@ const OPEN_RTB_PROTOCOL = { let mediaTypes = {}; if (bannerParams && bannerParams.sizes) { - const sizes = utils.parseSizesInput(bannerParams.sizes); + const sizes = parseSizesInput(bannerParams.sizes); // get banner sizes in form [{ w: , h: }, ...] const format = sizes.map(size => { @@ -607,10 +611,10 @@ const OPEN_RTB_PROTOCOL = { if (bannerParams.pos) mediaTypes['banner'].pos = bannerParams.pos; } - if (!utils.isEmpty(videoParams)) { + if (!isEmpty(videoParams)) { if (videoParams.context === 'outstream' && !videoParams.renderer && !adUnit.renderer) { // Don't push oustream w/o renderer to request object. - utils.logError('Outstream bid without renderer cannot be sent to Prebid Server.'); + logError('Outstream bid without renderer cannot be sent to Prebid Server.'); } else { if (videoParams.context === 'instream' && !videoParams.hasOwnProperty('placement')) { videoParams.placement = 1; @@ -619,8 +623,8 @@ const OPEN_RTB_PROTOCOL = { mediaTypes['video'] = Object.keys(videoParams).filter(param => param !== 'context') .reduce((result, param) => { if (param === 'playerSize') { - result.w = utils.deepAccess(videoParams, `${param}.0.0`); - result.h = utils.deepAccess(videoParams, `${param}.0.1`); + result.w = deepAccess(videoParams, `${param}.0.0`); + result.h = deepAccess(videoParams, `${param}.0.1`); } else { result[param] = videoParams[param]; } @@ -646,7 +650,7 @@ const OPEN_RTB_PROTOCOL = { ver: '1.2' } } catch (e) { - utils.logError('error creating native request: ' + String(e)) + logError('error creating native request: ' + String(e)) } } @@ -659,11 +663,11 @@ const OPEN_RTB_PROTOCOL = { } acc[bid.bidder] = (s2sConfig.adapterOptions && s2sConfig.adapterOptions[bid.bidder]) ? Object.assign({}, bid.params, s2sConfig.adapterOptions[bid.bidder]) : bid.params; return acc; - }, {...utils.deepAccess(adUnit, 'ortb2Imp.ext')}); + }, {...deepAccess(adUnit, 'ortb2Imp.ext')}); const imp = { id: impressionId, ext, secure: s2sConfig.secure }; - const ortb2 = {...utils.deepAccess(adUnit, 'ortb2Imp.ext.data')}; + const ortb2 = {...deepAccess(adUnit, 'ortb2Imp.ext.data')}; Object.keys(ortb2).forEach(prop => { /** * Prebid AdSlot @@ -671,7 +675,7 @@ const OPEN_RTB_PROTOCOL = { */ if (prop === 'pbadslot') { if (typeof ortb2[prop] === 'string' && ortb2[prop]) { - utils.deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]); + deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]); } else { // remove pbadslot property if it doesn't meet the spec delete imp.ext.data.pbadslot; @@ -682,13 +686,13 @@ const OPEN_RTB_PROTOCOL = { */ ['name', 'adslot'].forEach(name => { /** @type {(string|undefined)} */ - const value = utils.deepAccess(ortb2, `adserver.${name}`); + const value = deepAccess(ortb2, `adserver.${name}`); if (typeof value === 'string' && value) { - utils.deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value); + deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value); } }); } else { - utils.deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]); + deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]); } }); @@ -697,7 +701,7 @@ const OPEN_RTB_PROTOCOL = { // if storedAuctionResponse has been set, pass SRID const storedAuctionResponseBid = find(firstBidRequest.bids, bid => (bid.adUnitCode === adUnit.code && bid.storedAuctionResponse)); if (storedAuctionResponseBid) { - utils.deepSetValue(imp, 'ext.prebid.storedauctionresponse.id', storedAuctionResponseBid.storedAuctionResponse.toString()); + deepSetValue(imp, 'ext.prebid.storedauctionresponse.id', storedAuctionResponseBid.storedAuctionResponse.toString()); } const getFloorBid = find(firstBidRequest.bids, bid => bid.adUnitCode === adUnit.code && typeof bid.getFloor === 'function'); @@ -709,7 +713,7 @@ const OPEN_RTB_PROTOCOL = { currency: config.getConfig('currency.adServerCurrency') || DEFAULT_S2S_CURRENCY, }); } catch (e) { - utils.logError('PBS: getFloor threw an error: ', e); + logError('PBS: getFloor threw an error: ', e); } if (floorInfo && floorInfo.currency && !isNaN(parseFloat(floorInfo.floor))) { imp.bidfloor = parseFloat(floorInfo.floor); @@ -723,7 +727,7 @@ const OPEN_RTB_PROTOCOL = { }); if (!imps.length) { - utils.logError('Request to Prebid Server rejected due to invalid media type(s) in adUnit.'); + logError('Request to Prebid Server rejected due to invalid media type(s) in adUnit.'); return; } const request = { @@ -775,36 +779,36 @@ const OPEN_RTB_PROTOCOL = { _appendSiteAppDevice(request, bidRequests[0].refererInfo.referer, s2sConfig.accountId); // pass schain object if it is present - const schain = utils.deepAccess(bidRequests, '0.bids.0.schain'); + const schain = deepAccess(bidRequests, '0.bids.0.schain'); if (schain) { request.source.ext = { schain: schain }; } - if (!utils.isEmpty(aliases)) { + if (!isEmpty(aliases)) { request.ext.prebid.aliases = {...request.ext.prebid.aliases, ...aliases}; } - const bidUserIdAsEids = utils.deepAccess(bidRequests, '0.bids.0.userIdAsEids'); - if (utils.isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { - utils.deepSetValue(request, 'user.ext.eids', bidUserIdAsEids); + const bidUserIdAsEids = deepAccess(bidRequests, '0.bids.0.userIdAsEids'); + if (isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) { + deepSetValue(request, 'user.ext.eids', bidUserIdAsEids); } - if (utils.isArray(eidPermissions) && eidPermissions.length > 0) { - if (requestedBidders && utils.isArray(requestedBidders)) { + if (isArray(eidPermissions) && eidPermissions.length > 0) { + if (requestedBidders && isArray(requestedBidders)) { eidPermissions.forEach(i => { if (i.bidders) { i.bidders = i.bidders.filter(bidder => requestedBidders.includes(bidder)) } }); } - utils.deepSetValue(request, 'ext.prebid.data.eidpermissions', eidPermissions); + deepSetValue(request, 'ext.prebid.data.eidpermissions', eidPermissions); } const multibid = config.getConfig('multibid'); if (multibid) { - utils.deepSetValue(request, 'ext.prebid.multibid', multibid.reduce((result, i) => { + deepSetValue(request, 'ext.prebid.multibid', multibid.reduce((result, i) => { let obj = {}; Object.keys(i).forEach(key => { @@ -824,25 +828,25 @@ const OPEN_RTB_PROTOCOL = { if (typeof firstBidRequest.gdprConsent.gdprApplies === 'boolean') { gdprApplies = firstBidRequest.gdprConsent.gdprApplies ? 1 : 0; } - utils.deepSetValue(request, 'regs.ext.gdpr', gdprApplies); - utils.deepSetValue(request, 'user.ext.consent', firstBidRequest.gdprConsent.consentString); + deepSetValue(request, 'regs.ext.gdpr', gdprApplies); + deepSetValue(request, 'user.ext.consent', firstBidRequest.gdprConsent.consentString); if (firstBidRequest.gdprConsent.addtlConsent && typeof firstBidRequest.gdprConsent.addtlConsent === 'string') { - utils.deepSetValue(request, 'user.ext.ConsentedProvidersSettings.consented_providers', firstBidRequest.gdprConsent.addtlConsent); + deepSetValue(request, 'user.ext.ConsentedProvidersSettings.consented_providers', firstBidRequest.gdprConsent.addtlConsent); } } // US Privacy (CCPA) support if (firstBidRequest.uspConsent) { - utils.deepSetValue(request, 'regs.ext.us_privacy', firstBidRequest.uspConsent); + deepSetValue(request, 'regs.ext.us_privacy', firstBidRequest.uspConsent); } } if (getConfig('coppa') === true) { - utils.deepSetValue(request, 'regs.coppa', 1); + deepSetValue(request, 'regs.coppa', 1); } const commonFpd = getConfig('ortb2') || {}; - utils.mergeDeep(request, commonFpd); + mergeDeep(request, commonFpd); addBidderFirstPartyDataToRequest(request); @@ -862,7 +866,7 @@ const OPEN_RTB_PROTOCOL = { let bidRequest; let key = `${bid.impid}${seatbid.seat}`; if (bidIdMap[key]) { - bidRequest = utils.getBidRequest( + bidRequest = getBidRequest( bidIdMap[key], bidderRequests ); @@ -879,31 +883,31 @@ const OPEN_RTB_PROTOCOL = { // temporarily leaving attaching it to each bidResponse so no breaking change // BUT: this is a flat map, so it should be only attached to bidderRequest, a the change above does - let serverResponseTimeMs = utils.deepAccess(response, ['ext', 'responsetimemillis', seatbid.seat].join('.')); + let serverResponseTimeMs = deepAccess(response, ['ext', 'responsetimemillis', seatbid.seat].join('.')); if (bidRequest && serverResponseTimeMs) { bidRequest.serverResponseTimeMs = serverResponseTimeMs; } // Look for seatbid[].bid[].ext.prebid.bidid and place it in the bidResponse object for use in analytics adapters as 'pbsBidId' - const bidId = utils.deepAccess(bid, 'ext.prebid.bidid'); - if (utils.isStr(bidId)) { + const bidId = deepAccess(bid, 'ext.prebid.bidid'); + if (isStr(bidId)) { bidObject.pbsBidId = bidId; } // store wurl by auctionId and adId so it can be accessed from the BID_WON event handler - if (utils.isStr(utils.deepAccess(bid, 'ext.prebid.events.win'))) { - addWurl(bidRequest.auctionId, bidObject.adId, utils.deepAccess(bid, 'ext.prebid.events.win')); + if (isStr(deepAccess(bid, 'ext.prebid.events.win'))) { + addWurl(bidRequest.auctionId, bidObject.adId, deepAccess(bid, 'ext.prebid.events.win')); } - let extPrebidTargeting = utils.deepAccess(bid, 'ext.prebid.targeting'); + let extPrebidTargeting = deepAccess(bid, 'ext.prebid.targeting'); // If ext.prebid.targeting exists, add it as a property value named 'adserverTargeting' // The removal of hb_winurl and hb_bidid targeting values is temporary // once we get through the transition, this block will be removed. - if (utils.isPlainObject(extPrebidTargeting)) { + if (isPlainObject(extPrebidTargeting)) { // If wurl exists, remove hb_winurl and hb_bidid targeting attributes - if (utils.isStr(utils.deepAccess(bid, 'ext.prebid.events.win'))) { - extPrebidTargeting = utils.getDefinedParams(extPrebidTargeting, Object.keys(extPrebidTargeting) + if (isStr(deepAccess(bid, 'ext.prebid.events.win'))) { + extPrebidTargeting = getDefinedParams(extPrebidTargeting, Object.keys(extPrebidTargeting) .filter(i => (i.indexOf('hb_winurl') === -1 && i.indexOf('hb_bidid') === -1))); } bidObject.adserverTargeting = extPrebidTargeting; @@ -911,7 +915,7 @@ const OPEN_RTB_PROTOCOL = { bidObject.seatBidId = bid.id; - if (utils.deepAccess(bid, 'ext.prebid.type') === VIDEO) { + if (deepAccess(bid, 'ext.prebid.type') === VIDEO) { bidObject.mediaType = VIDEO; let sizes = bidRequest.sizes && bidRequest.sizes[0]; bidObject.playerWidth = sizes[0]; @@ -930,7 +934,7 @@ const OPEN_RTB_PROTOCOL = { if (bid.adm) { bidObject.vastXml = bid.adm; } if (!bidObject.vastUrl && bid.nurl) { bidObject.vastUrl = bid.nurl; } - } else if (utils.deepAccess(bid, 'ext.prebid.type') === NATIVE) { + } else if (deepAccess(bid, 'ext.prebid.type') === NATIVE) { bidObject.mediaType = NATIVE; let adm; if (typeof bid.adm === 'string') { @@ -956,18 +960,18 @@ const OPEN_RTB_PROTOCOL = { }); } - if (utils.isPlainObject(adm) && Array.isArray(adm.assets)) { + if (isPlainObject(adm) && Array.isArray(adm.assets)) { let origAssets = nativeAssetCache[bid.impid]; - bidObject.native = utils.cleanObj(adm.assets.reduce((native, asset) => { + bidObject.native = cleanObj(adm.assets.reduce((native, asset) => { let origAsset = origAssets[asset.id]; - if (utils.isPlainObject(asset.img)) { - native[origAsset.img.type ? nativeImgIdMap[origAsset.img.type] : 'image'] = utils.pick( + if (isPlainObject(asset.img)) { + native[origAsset.img.type ? nativeImgIdMap[origAsset.img.type] : 'image'] = pick( asset.img, ['url', 'w as width', 'h as height'] ); - } else if (utils.isPlainObject(asset.title)) { + } else if (isPlainObject(asset.title)) { native['title'] = asset.title.text - } else if (utils.isPlainObject(asset.data)) { + } else if (isPlainObject(asset.data)) { nativeDataNames.forEach(dataType => { if (nativeDataIdMap[dataType] === origAsset.data.type) { native[dataType] = asset.data.value; @@ -975,19 +979,19 @@ const OPEN_RTB_PROTOCOL = { }); } return native; - }, utils.cleanObj({ + }, cleanObj({ clickUrl: adm.link, - clickTrackers: utils.deepAccess(adm, 'link.clicktrackers'), + clickTrackers: deepAccess(adm, 'link.clicktrackers'), impressionTrackers: trackers[nativeEventTrackerMethodMap.img], javascriptTrackers: trackers[nativeEventTrackerMethodMap.js] }))); } else { - utils.logError('prebid server native response contained no assets'); + logError('prebid server native response contained no assets'); } } else { // banner if (bid.adm && bid.nurl) { bidObject.ad = bid.adm; - bidObject.ad += utils.createTrackPixelHtml(decodeURIComponent(bid.nurl)); + bidObject.ad += createTrackPixelHtml(decodeURIComponent(bid.nurl)); } else if (bid.adm) { bidObject.ad = bid.adm; } else if (bid.nurl) { @@ -1004,8 +1008,8 @@ const OPEN_RTB_PROTOCOL = { if (bid.burl) { bidObject.burl = bid.burl; } bidObject.currency = (response.cur) ? response.cur : DEFAULT_S2S_CURRENCY; bidObject.meta = {}; - let extPrebidMeta = utils.deepAccess(bid, 'ext.prebid.meta'); - if (extPrebidMeta && utils.isPlainObject(extPrebidMeta)) { bidObject.meta = utils.deepClone(extPrebidMeta); } + let extPrebidMeta = deepAccess(bid, 'ext.prebid.meta'); + if (extPrebidMeta && isPlainObject(extPrebidMeta)) { bidObject.meta = deepClone(extPrebidMeta); } if (bid.adomain) { bidObject.meta.advertiserDomains = bid.adomain; } // the OpenRTB location for "TTL" as understood by Prebid.js is "exp" (expiration). @@ -1028,9 +1032,9 @@ const OPEN_RTB_PROTOCOL = { */ function bidWonHandler(bid) { const wurl = getWurl(bid.auctionId, bid.adId); - if (utils.isStr(wurl)) { - utils.logMessage(`Invoking image pixel for wurl on BID_WIN: "${wurl}"`); - utils.triggerPixel(wurl); + if (isStr(wurl)) { + logMessage(`Invoking image pixel for wurl on BID_WIN: "${wurl}"`); + triggerPixel(wurl); // remove from wurl cache, since the wurl url was called removeWurl(bid.auctionId, bid.adId); @@ -1041,7 +1045,7 @@ function hasPurpose1Consent(gdprConsent) { let result = true; if (gdprConsent) { if (gdprConsent.gdprApplies && gdprConsent.apiVersion === 2) { - result = !!(utils.deepAccess(gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(deepAccess(gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -1068,7 +1072,7 @@ export function PrebidServer() { /* Prebid executes this function when the page asks to send out bid requests */ baseAdapter.callBids = function(s2sBidRequest, bidRequests, addBidResponse, done, ajax) { - const adUnits = utils.deepClone(s2sBidRequest.ad_units); + const adUnits = deepClone(s2sBidRequest.ad_units); let { gdprConsent, uspConsent } = getConsentData(bidRequests); // at this point ad units should have a size array either directly or mapped so filter for that @@ -1078,9 +1082,9 @@ export function PrebidServer() { // in case config.bidders contains invalid bidders, we only process those we sent requests for const requestedBidders = validAdUnits - .map(adUnit => adUnit.bids.map(bid => bid.bidder).filter(utils.uniques)) - .reduce(utils.flatten) - .filter(utils.uniques); + .map(adUnit => adUnit.bids.map(bid => bid.bidder).filter(uniques)) + .reduce(flatten) + .filter(uniques); if (Array.isArray(_s2sConfigs)) { if (s2sBidRequest.s2sConfig && s2sBidRequest.s2sConfig.syncEndpoint && getMatchingConsentUrl(s2sBidRequest.s2sConfig.syncEndpoint, gdprConsent)) { @@ -1093,7 +1097,7 @@ export function PrebidServer() { const request = OPEN_RTB_PROTOCOL.buildRequest(s2sBidRequest, bidRequests, validAdUnits, s2sBidRequest.s2sConfig, requestedBidders); const requestJson = request && JSON.stringify(request); - utils.logInfo('BidRequest: ' + requestJson); + logInfo('BidRequest: ' + requestJson); const endpointUrl = getMatchingConsentUrl(s2sBidRequest.s2sConfig.endpoint, gdprConsent); if (request && requestJson && endpointUrl) { ajax( @@ -1106,7 +1110,7 @@ export function PrebidServer() { { contentType: 'text/plain', withCredentials: true } ); } else { - utils.logError('PBS request not made. Check endpoints.'); + logError('PBS request not made. Check endpoints.'); } } }; @@ -1134,11 +1138,11 @@ export function PrebidServer() { bidderRequests.forEach(bidderRequest => events.emit(CONSTANTS.EVENTS.BIDDER_DONE, bidderRequest)); } catch (error) { - utils.logError(error); + logError(error); } if (!result || (result.status && includes(result.status, 'Error'))) { - utils.logError('error parsing response: ', result.status); + logError('error parsing response: ', result.status); } done(); diff --git a/modules/rtdModule/index.js b/modules/rtdModule/index.js index e235868f791..7dce09f0d1d 100644 --- a/modules/rtdModule/index.js +++ b/modules/rtdModule/index.js @@ -143,7 +143,7 @@ import {config} from '../../src/config.js'; import {module} from '../../src/hook.js'; -import * as utils from '../../src/utils.js'; +import { logError, logWarn } from '../../src/utils.js'; import events from '../../src/events.js'; import CONSTANTS from '../../src/constants.json'; import {gdprDataHandler, uspDataHandler} from '../../src/adapterManager.js'; @@ -174,7 +174,7 @@ export function attachRealTimeDataProvider(submodule) { export function init(config) { const confListener = config.getConfig(MODULE_NAME, ({realTimeData}) => { if (!realTimeData.dataProviders) { - utils.logError('missing parameters for real time module'); + logError('missing parameters for real time module'); return; } confListener(); // unsubscribe config listener @@ -314,7 +314,7 @@ export function getAdUnitTargeting(auction) { if (smTargeting && typeof smTargeting === 'object') { targeting.push(smTargeting); } else { - utils.logWarn('invalid getTargetingData response for sub module', relevantSubModules[i].name); + logWarn('invalid getTargetingData response for sub module', relevantSubModules[i].name); } } // place data on auction adUnits diff --git a/modules/userId/eids.js b/modules/userId/eids.js index 0a8e94883b4..0f159c4f33b 100644 --- a/modules/userId/eids.js +++ b/modules/userId/eids.js @@ -1,4 +1,4 @@ -import * as utils from '../../src/utils.js'; +import { pick, isFn, isStr, isPlainObject, deepAccess } from '../../src/utils.js'; // Each user-id sub-module is expected to mention respective config here const USER_IDS_CONFIG = { @@ -64,7 +64,7 @@ const USER_IDS_CONFIG = { return null; }, getUidExt: function(parrableId) { - const extendedData = utils.pick(parrableId, [ + const extendedData = pick(parrableId, [ 'ibaOptout', 'ccpaOptout' ]); @@ -248,11 +248,11 @@ function createEidObject(userIdData, subModuleKey) { if (conf && userIdData) { let eid = {}; eid.source = conf['source']; - const value = utils.isFn(conf['getValue']) ? conf['getValue'](userIdData) : userIdData; - if (utils.isStr(value)) { + const value = isFn(conf['getValue']) ? conf['getValue'](userIdData) : userIdData; + if (isStr(value)) { const uid = { id: value, atype: conf['atype'] }; // getUidExt - if (utils.isFn(conf['getUidExt'])) { + if (isFn(conf['getUidExt'])) { const uidExt = conf['getUidExt'](userIdData); if (uidExt) { uid.ext = uidExt; @@ -260,7 +260,7 @@ function createEidObject(userIdData, subModuleKey) { } eid.uids = [uid]; // getEidExt - if (utils.isFn(conf['getEidExt'])) { + if (isFn(conf['getEidExt'])) { const eidExt = conf['getEidExt'](userIdData); if (eidExt) { eid.ext = eidExt; @@ -297,11 +297,11 @@ export function createEidsArray(bidRequestUserId) { */ export function buildEidPermissions(submodules) { let eidPermissions = []; - submodules.filter(i => utils.isPlainObject(i.idObj) && Object.keys(i.idObj).length) + submodules.filter(i => isPlainObject(i.idObj) && Object.keys(i.idObj).length) .forEach(i => { Object.keys(i.idObj).forEach(key => { - if (utils.deepAccess(i, 'config.bidders') && Array.isArray(i.config.bidders) && - utils.deepAccess(USER_IDS_CONFIG, key + '.source')) { + if (deepAccess(i, 'config.bidders') && Array.isArray(i.config.bidders) && + deepAccess(USER_IDS_CONFIG, key + '.source')) { eidPermissions.push( { source: USER_IDS_CONFIG[key].source, diff --git a/modules/userId/index.js b/modules/userId/index.js index a6a824fe89e..b0293a9c26a 100644 --- a/modules/userId/index.js +++ b/modules/userId/index.js @@ -133,14 +133,16 @@ import find from 'core-js-pure/features/array/find.js'; import { config } from '../../src/config.js'; import events from '../../src/events.js'; -import * as utils from '../../src/utils.js'; import { getGlobal } from '../../src/prebidGlobal.js'; import { gdprDataHandler } from '../../src/adapterManager.js'; import CONSTANTS from '../../src/constants.json'; import { module, hook } from '../../src/hook.js'; import { createEidsArray, buildEidPermissions } from './eids.js'; import { getCoreStorageManager } from '../../src/storageManager.js'; -import {getPrebidInternal} from '../../src/utils.js'; +import { + getPrebidInternal, isPlainObject, logError, isArray, cyrb53Hash, deepAccess, timestamp, delayExecution, logInfo, isFn, + logWarn, isEmptyStr, isNumber +} from '../../src/utils.js'; import includes from 'core-js-pure/features/array/includes.js'; const MODULE_NAME = 'User ID'; @@ -199,7 +201,7 @@ export function setStoredValue(submodule, value) { const domainOverride = (typeof submodule.submodule.domainOverride === 'function') ? submodule.submodule.domainOverride() : null; try { - const valueStr = utils.isPlainObject(value) ? JSON.stringify(value) : value; + const valueStr = isPlainObject(value) ? JSON.stringify(value) : value; const expiresStr = (new Date(Date.now() + (storage.expires * (60 * 60 * 24 * 1000)))).toUTCString(); if (storage.type === COOKIE) { coreStorage.setCookie(storage.name, valueStr, expiresStr, 'Lax', domainOverride); @@ -214,13 +216,13 @@ export function setStoredValue(submodule, value) { } } } catch (error) { - utils.logError(error); + logError(error); } } function setPrebidServerEidPermissions(initializedSubmodules) { let setEidPermissions = getPrebidInternal().setEidPermissions; - if (typeof setEidPermissions === 'function' && utils.isArray(initializedSubmodules)) { + if (typeof setEidPermissions === 'function' && isArray(initializedSubmodules)) { setEidPermissions(buildEidPermissions(initializedSubmodules)); } } @@ -253,7 +255,7 @@ function getStoredValue(storage, key = undefined) { storedValue = JSON.parse(storedValue); } } catch (e) { - utils.logError(e); + logError(e); } return storedValue; } @@ -278,7 +280,7 @@ function makeStoredConsentDataHash(consentData) { storedConsentData.apiVersion = consentData.apiVersion; } - return utils.cyrb53Hash(JSON.stringify(storedConsentData)); + return cyrb53Hash(JSON.stringify(storedConsentData)); } /** @@ -290,7 +292,7 @@ export function setStoredConsentData(consentData) { const expiresStr = (new Date(Date.now() + (CONSENT_DATA_COOKIE_STORAGE_CONFIG.expires * (60 * 60 * 24 * 1000)))).toUTCString(); coreStorage.setCookie(CONSENT_DATA_COOKIE_STORAGE_CONFIG.name, makeStoredConsentDataHash(consentData), expiresStr, 'Lax'); } catch (error) { - utils.logError(error); + logError(error); } } @@ -302,7 +304,7 @@ function getStoredConsentData() { try { return coreStorage.getCookie(CONSENT_DATA_COOKIE_STORAGE_CONFIG.name); } catch (e) { - utils.logError(e); + logError(e); } } @@ -332,10 +334,10 @@ function hasGDPRConsent(consentData) { if (!consentData.consentString) { return false; } - if (consentData.apiVersion === 1 && utils.deepAccess(consentData, 'vendorData.purposeConsents.1') === false) { + if (consentData.apiVersion === 1 && deepAccess(consentData, 'vendorData.purposeConsents.1') === false) { return false; } - if (consentData.apiVersion === 2 && utils.deepAccess(consentData, 'vendorData.purpose.consents.1') === false) { + if (consentData.apiVersion === 2 && deepAccess(consentData, 'vendorData.purpose.consents.1') === false) { return false; } } @@ -363,7 +365,7 @@ export function findRootDomain(fullDomain = window.location.hostname) { const TEST_COOKIE_VALUE = 'writeable'; do { rootDomain = domainParts.slice(startIndex).join('.'); - let expirationDate = new Date(utils.timestamp() + 10 * 1000).toUTCString(); + let expirationDate = new Date(timestamp() + 10 * 1000).toUTCString(); // Write a test cookie coreStorage.setCookie( @@ -403,7 +405,7 @@ export function findRootDomain(fullDomain = window.location.hostname) { function processSubmoduleCallbacks(submodules, cb) { let done = () => {}; if (cb) { - done = utils.delayExecution(() => { + done = delayExecution(() => { clearTimeout(timeoutID); cb(); }, submodules.length); @@ -418,7 +420,7 @@ function processSubmoduleCallbacks(submodules, cb) { // cache decoded value (this is copied to every adUnit bid) submodule.idObj = submodule.submodule.decode(idObj, submodule.config); } else { - utils.logInfo(`${MODULE_NAME}: ${submodule.submodule.name} - request id responded with an empty value`); + logInfo(`${MODULE_NAME}: ${submodule.submodule.name} - request id responded with an empty value`); } done(); }); @@ -436,7 +438,7 @@ function getCombinedSubmoduleIds(submodules) { if (!Array.isArray(submodules) || !submodules.length) { return {}; } - const combinedSubmoduleIds = submodules.filter(i => utils.isPlainObject(i.idObj) && Object.keys(i.idObj).length).reduce((carry, i) => { + const combinedSubmoduleIds = submodules.filter(i => isPlainObject(i.idObj) && Object.keys(i.idObj).length).reduce((carry, i) => { Object.keys(i.idObj).forEach(key => { carry[key] = i.idObj[key]; }); @@ -456,8 +458,8 @@ function getCombinedSubmoduleIdsForBidder(submodules, bidder) { return {}; } return submodules - .filter(i => !i.config.bidders || !utils.isArray(i.config.bidders) || includes(i.config.bidders, bidder)) - .filter(i => utils.isPlainObject(i.idObj) && Object.keys(i.idObj).length) + .filter(i => !i.config.bidders || !isArray(i.config.bidders) || includes(i.config.bidders, bidder)) + .filter(i => isPlainObject(i.idObj) && Object.keys(i.idObj).length) .reduce((carry, i) => { Object.keys(i.idObj).forEach(key => { carry[key] = i.idObj[key]; @@ -475,7 +477,7 @@ function addIdDataToAdUnitBids(adUnits, submodules) { return; } adUnits.forEach(adUnit => { - if (adUnit.bids && utils.isArray(adUnit.bids)) { + if (adUnit.bids && isArray(adUnit.bids)) { adUnit.bids.forEach(bid => { const combinedSubmoduleIds = getCombinedSubmoduleIdsForBidder(submodules, bid.bidder); if (Object.keys(combinedSubmoduleIds).length) { @@ -500,7 +502,7 @@ function initializeSubmodulesAndExecuteCallbacks(continueAuction) { if (initializedSubmodules.length) { setPrebidServerEidPermissions(initializedSubmodules); // list of submodules that have callbacks that need to be executed - const submodulesWithCallbacks = initializedSubmodules.filter(item => utils.isFn(item.callback)); + const submodulesWithCallbacks = initializedSubmodules.filter(item => isFn(item.callback)); if (submodulesWithCallbacks.length) { if (continueAuction && auctionDelay > 0) { @@ -513,7 +515,7 @@ function initializeSubmodulesAndExecuteCallbacks(continueAuction) { continueAuction(); } } - utils.logInfo(`${MODULE_NAME} - auction delayed by ${auctionDelay} at most to fetch ids`); + logInfo(`${MODULE_NAME} - auction delayed by ${auctionDelay} at most to fetch ids`); timeoutID = setTimeout(continueCallback, auctionDelay); processSubmoduleCallbacks(submodulesWithCallbacks, continueCallback); @@ -596,7 +598,7 @@ function refreshUserIds(options, callback) { // gdpr consent with purpose one is required, otherwise exit immediately let {userIdModules, hasValidated} = validateGdprEnforcement(submodules, consentData); if (!hasValidated && !hasGDPRConsent(consentData)) { - utils.logWarn(`${MODULE_NAME} - gdpr permission not valid for local storage or cookies, exit module`); + logWarn(`${MODULE_NAME} - gdpr permission not valid for local storage or cookies, exit module`); return; } @@ -611,7 +613,7 @@ function refreshUserIds(options, callback) { continue; } - utils.logInfo(`${MODULE_NAME} - refreshing ${submodule.submodule.name}`); + logInfo(`${MODULE_NAME} - refreshing ${submodule.submodule.name}`); populateSubmoduleId(submodule, consentData, storedConsentData, true); updateInitializedSubmodules(submodule); @@ -619,7 +621,7 @@ function refreshUserIds(options, callback) { setPrebidServerEidPermissions(initializedSubmodules); } - if (utils.isFn(submodule.callback)) { + if (isFn(submodule.callback)) { callbackSubmodules.push(submodule); } } @@ -663,7 +665,7 @@ function populateSubmoduleId(submodule, consentData, storedConsentData, forceRef response = submodule.submodule.extendId(submodule.config, consentData, storedId); } - if (utils.isPlainObject(response)) { + if (isPlainObject(response)) { if (response.id) { // A getId/extendId result assumed to be valid user id data, which should be saved to users local storage or cookies setStoredValue(submodule, response.id); @@ -685,7 +687,7 @@ function populateSubmoduleId(submodule, consentData, storedConsentData, forceRef submodule.idObj = submodule.config.value; } else { const response = submodule.submodule.getId(submodule.config, consentData, undefined); - if (utils.isPlainObject(response)) { + if (isPlainObject(response)) { if (typeof response.callback === 'function') { submodule.callback = response.callback; } if (response.id) { submodule.idObj = submodule.submodule.decode(response.id, submodule.config); } } @@ -701,7 +703,7 @@ function initSubmodules(submodules, consentData) { // gdpr consent with purpose one is required, otherwise exit immediately let { userIdModules, hasValidated } = validateGdprEnforcement(submodules, consentData); if (!hasValidated && !hasGDPRConsent(consentData)) { - utils.logWarn(`${MODULE_NAME} - gdpr permission not valid for local storage or cookies, exit module`); + logWarn(`${MODULE_NAME} - gdpr permission not valid for local storage or cookies, exit module`); return []; } @@ -746,17 +748,17 @@ function getValidSubmoduleConfigs(configRegistry, submoduleRegistry, activeStora } return configRegistry.reduce((carry, config) => { // every submodule config obj must contain a valid 'name' - if (!config || utils.isEmptyStr(config.name)) { + if (!config || isEmptyStr(config.name)) { return carry; } // Validate storage config contains 'type' and 'name' properties with non-empty string values // 'type' must be a value currently enabled in the browser if (config.storage && - !utils.isEmptyStr(config.storage.type) && - !utils.isEmptyStr(config.storage.name) && + !isEmptyStr(config.storage.type) && + !isEmptyStr(config.storage.name) && activeStorageTypes.indexOf(config.storage.type) !== -1) { carry.push(config); - } else if (utils.isPlainObject(config.value)) { + } else if (isPlainObject(config.value)) { carry.push(config); } else if (!config.storage && !config.value) { carry.push(config); @@ -793,7 +795,7 @@ function updateSubmodules() { if (!addedUserIdHook && submodules.length) { // priority value 40 will load after consentManagement with a priority of 50 getGlobal().requestBids.before(requestBidsHook, 40); - utils.logInfo(`${MODULE_NAME} - usersync config updated for ${submodules.length} submodules: `, submodules.map(a => a.submodule.name)); + logInfo(`${MODULE_NAME} - usersync config updated for ${submodules.length} submodules: `, submodules.map(a => a.submodule.name)); addedUserIdHook = true; } } @@ -828,11 +830,11 @@ export function init(config) { // exit immediately if opt out cookie or local storage keys exists. if (validStorageTypes.indexOf(COOKIE) !== -1 && coreStorage.getCookie(PBJS_USER_ID_OPTOUT_NAME)) { - utils.logInfo(`${MODULE_NAME} - opt-out cookie found, exit module`); + logInfo(`${MODULE_NAME} - opt-out cookie found, exit module`); return; } if (validStorageTypes.indexOf(LOCAL_STORAGE) !== -1 && coreStorage.getDataFromLocalStorage(PBJS_USER_ID_OPTOUT_NAME)) { - utils.logInfo(`${MODULE_NAME} - opt-out localStorage found, exit module`); + logInfo(`${MODULE_NAME} - opt-out localStorage found, exit module`); return; } @@ -842,8 +844,8 @@ export function init(config) { const userSync = conf.userSync; if (userSync && userSync.userIds) { configRegistry = userSync.userIds; - syncDelay = utils.isNumber(userSync.syncDelay) ? userSync.syncDelay : DEFAULT_SYNC_DELAY; - auctionDelay = utils.isNumber(userSync.auctionDelay) ? userSync.auctionDelay : NO_AUCTION_DELAY; + syncDelay = isNumber(userSync.syncDelay) ? userSync.syncDelay : DEFAULT_SYNC_DELAY; + auctionDelay = isNumber(userSync.auctionDelay) ? userSync.auctionDelay : NO_AUCTION_DELAY; updateSubmodules(); } }); diff --git a/modules/validationFpdModule/index.js b/modules/validationFpdModule/index.js index a1d1a3823f0..2db170c1bd1 100644 --- a/modules/validationFpdModule/index.js +++ b/modules/validationFpdModule/index.js @@ -3,7 +3,7 @@ * @module modules/firstPartyData */ import { config } from '../../src/config.js'; -import * as utils from '../../src/utils.js'; +import { isEmpty, isNumber, logWarn, deepAccess } from '../../src/utils.js'; import { ORTB_MAP } from './config.js'; import { submodule } from '../../src/hook.js'; import { getStorageManager } from '../../src/storageManager.js'; @@ -19,9 +19,9 @@ let optout; function isEmptyData(data) { let check = true; - if (typeof data === 'object' && !utils.isEmpty(data)) { + if (typeof data === 'object' && !isEmpty(data)) { check = false; - } else if (typeof data !== 'object' && (utils.isNumber(data) || data)) { + } else if (typeof data !== 'object' && (isNumber(data) || data)) { check = false; } @@ -42,7 +42,7 @@ function getRequiredData(obj, required, parent, i) { required.forEach(key => { if (!obj[key] || isEmptyData(obj[key])) { check = false; - utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: missing required property ${key}`); + logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: missing required property ${key}`); } }); @@ -91,17 +91,17 @@ export function filterArrayData(arr, child, path, parent) { return true; } - utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); + logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); }).filter((index, i) => { let requiredCheck = true; - let mapping = utils.deepAccess(ORTB_MAP, path); + let mapping = deepAccess(ORTB_MAP, path); if (mapping && mapping.required) requiredCheck = getRequiredData(index, mapping.required, parent, i); if (requiredCheck) return true; }).reduce((result, value, i) => { let typeBool = false; - let mapping = utils.deepAccess(ORTB_MAP, path); + let mapping = deepAccess(ORTB_MAP, path); switch (child.type) { case 'string': @@ -126,7 +126,7 @@ export function filterArrayData(arr, child, path, parent) { break; } - if (!typeBool) utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); + if (!typeBool) logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); return result; }, []); @@ -146,26 +146,26 @@ export function validateFpd(fpd, path = '', parent = '') { // Filter out imp property if exists let validObject = Object.assign({}, Object.keys(fpd).filter(key => { - let mapping = utils.deepAccess(ORTB_MAP, path + key); + let mapping = deepAccess(ORTB_MAP, path + key); if (!mapping || !mapping.invalid) return key; - utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: invalid property`); + logWarn(`Filtered ${parent}${key} property in ortb2 data: invalid property`); }).filter(key => { - let mapping = utils.deepAccess(ORTB_MAP, path + key); + let mapping = deepAccess(ORTB_MAP, path + key); // let typeBool = false; let typeBool = (mapping) ? typeValidation(fpd[key], {type: mapping.type, isArray: mapping.isArray}) : true; if (typeBool || !mapping) return key; - utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: expected type ${(mapping.isArray) ? 'array' : mapping.type}`); + logWarn(`Filtered ${parent}${key} property in ortb2 data: expected type ${(mapping.isArray) ? 'array' : mapping.type}`); }).reduce((result, key) => { - let mapping = utils.deepAccess(ORTB_MAP, path + key); + let mapping = deepAccess(ORTB_MAP, path + key); let modified = {}; if (mapping) { if (mapping.optoutApplies && optout) { - utils.logWarn(`Filtered ${parent}${key} data: pubcid optout found`); + logWarn(`Filtered ${parent}${key} data: pubcid optout found`); return result; } @@ -176,7 +176,7 @@ export function validateFpd(fpd, path = '', parent = '') { // Check if modified data has data and return (!isEmptyData(modified)) ? result[key] = modified - : utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: empty data found`); + : logWarn(`Filtered ${parent}${key} property in ortb2 data: empty data found`); } else { result[key] = fpd[key]; } From 9e0c0d26ca337f12cd00b57a2f2c62c5a7bcff4d Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 12:59:56 -0700 Subject: [PATCH 31/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7496) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/seedtagBidAdapter.js | 20 ++-- modules/sharedIdSystem.js | 22 ++-- modules/sharethroughAnalyticsAdapter.js | 16 +-- modules/sharethroughBidAdapter.js | 16 +-- modules/showheroes-bsBidAdapter.js | 46 ++++---- modules/sigmoidAnalyticsAdapter.js | 9 +- modules/sirdataRtdProvider.js | 68 +++++------ modules/sizeMappingV2.js | 78 ++++++------- modules/smaatoBidAdapter.js | 88 +++++++-------- modules/smartadserverBidAdapter.js | 14 +-- modules/smartxBidAdapter.js | 144 ++++++++++++------------ modules/smartyadsBidAdapter.js | 4 +- modules/smilewantedBidAdapter.js | 12 +- modules/sonobiAnalyticsAdapter.js | 46 ++++---- modules/sortableAnalyticsAdapter.js | 10 +- 15 files changed, 296 insertions(+), 297 deletions(-) diff --git a/modules/seedtagBidAdapter.js b/modules/seedtagBidAdapter.js index 8b7629df211..cb646fe10c3 100644 --- a/modules/seedtagBidAdapter.js +++ b/modules/seedtagBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js' +import { isArray, _map, triggerPixel } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { VIDEO, BANNER } from '../src/mediaTypes.js' @@ -62,13 +62,13 @@ function hasMandatoryVideoParams(bid) { const videoParams = getVideoParams(bid) return hasVideoMediaType(bid) && !!videoParams.playerSize && - utils.isArray(videoParams.playerSize) && + isArray(videoParams.playerSize) && videoParams.playerSize.length > 0; } function buildBidRequest(validBidRequest) { const params = validBidRequest.params; - const mediaTypes = utils._map( + const mediaTypes = _map( Object.keys(validBidRequest.mediaTypes), function (pbjsType) { return mediaTypesMap[pbjsType]; @@ -145,8 +145,8 @@ function buildBidResponse(seedtagBid) { export function getTimeoutUrl (data) { let queryParams = ''; if ( - utils.isArray(data) && data[0] && - utils.isArray(data[0].params) && data[0].params[0] + isArray(data) && data[0] && + isArray(data[0].params) && data[0].params[0] ) { const params = data[0].params[0]; queryParams = @@ -186,7 +186,7 @@ export const spec = { timeout: bidderRequest.timeout, version: '$prebid.version$', connectionType: getConnectionType(), - bidRequests: utils._map(validBidRequests, buildBidRequest) + bidRequests: _map(validBidRequests, buildBidRequest) }; if (payload.cmp) { @@ -211,8 +211,8 @@ export const spec = { */ interpretResponse: function(serverResponse) { const serverBody = serverResponse.body; - if (serverBody && serverBody.bids && utils.isArray(serverBody.bids)) { - return utils._map(serverBody.bids, function(bid) { + if (serverBody && serverBody.bids && isArray(serverBody.bids)) { + return _map(serverBody.bids, function(bid) { return buildBidResponse(bid); }); } else { @@ -243,7 +243,7 @@ export const spec = { */ onTimeout(data) { const url = getTimeoutUrl(data); - utils.triggerPixel(url); + triggerPixel(url); }, /** @@ -252,7 +252,7 @@ export const spec = { */ onBidWon: function (bid) { if (bid && bid.nurl) { - utils.triggerPixel(bid.nurl); + triggerPixel(bid.nurl); } } } diff --git a/modules/sharedIdSystem.js b/modules/sharedIdSystem.js index 2e3abd6b1a2..0c25a1747f6 100644 --- a/modules/sharedIdSystem.js +++ b/modules/sharedIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; +import { parseUrl, buildUrl, triggerPixel, logInfo, hasDeviceAccess, generateUUID } from '../src/utils.js'; import {submodule} from '../src/hook.js'; import { coppaDataHandler } from '../src/adapterManager.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -53,12 +53,12 @@ function queuePixelCallback(pixelUrl, id = '', callback) { } // Use pubcid as a cache buster - const urlInfo = utils.parseUrl(pixelUrl); + const urlInfo = parseUrl(pixelUrl); urlInfo.search.id = encodeURIComponent('pubcid:' + id); - const targetUrl = utils.buildUrl(urlInfo); + const targetUrl = buildUrl(urlInfo); return function () { - utils.triggerPixel(targetUrl); + triggerPixel(targetUrl); }; } @@ -89,10 +89,10 @@ export const sharedIdSystemSubmodule = { */ decode(value, config) { if (hasOptedOut()) { - utils.logInfo('PubCommonId decode: Has opted-out'); + logInfo('PubCommonId decode: Has opted-out'); return undefined; } - utils.logInfo(' Decoded value PubCommonId ' + value); + logInfo(' Decoded value PubCommonId ' + value); const idObj = {'pubcid': value}; return idObj; }, @@ -106,13 +106,13 @@ export const sharedIdSystemSubmodule = { */ getId: function (config = {}, consentData, storedId) { if (hasOptedOut()) { - utils.logInfo('PubCommonId: Has opted-out'); + logInfo('PubCommonId: Has opted-out'); return; } const coppa = coppaDataHandler.getCoppa(); if (coppa) { - utils.logInfo('PubCommonId: IDs not provided for coppa requests, exiting PubCommonId'); + logInfo('PubCommonId: IDs not provided for coppa requests, exiting PubCommonId'); return; } const {params: {create = true, pixelUrl} = {}} = config; @@ -126,7 +126,7 @@ export const sharedIdSystemSubmodule = { } catch (e) { } - if (!newId) newId = (create && utils.hasDeviceAccess()) ? utils.generateUUID() : undefined; + if (!newId) newId = (create && hasDeviceAccess()) ? generateUUID() : undefined; } const pixelCallback = queuePixelCallback(pixelUrl, newId); @@ -153,12 +153,12 @@ export const sharedIdSystemSubmodule = { */ extendId: function(config = {}, consentData, storedId) { if (hasOptedOut()) { - utils.logInfo('PubCommonId: Has opted-out'); + logInfo('PubCommonId: Has opted-out'); return {id: undefined}; } const coppa = coppaDataHandler.getCoppa(); if (coppa) { - utils.logInfo('PubCommonId: IDs not provided for coppa requests, exiting PubCommonId'); + logInfo('PubCommonId: IDs not provided for coppa requests, exiting PubCommonId'); return; } const {params: {extend = false, pixelUrl} = {}} = config; diff --git a/modules/sharethroughAnalyticsAdapter.js b/modules/sharethroughAnalyticsAdapter.js index 5147b2a4275..4f065cbca23 100644 --- a/modules/sharethroughAnalyticsAdapter.js +++ b/modules/sharethroughAnalyticsAdapter.js @@ -1,6 +1,6 @@ +import { tryAppendQueryString } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; -const utils = require('../src/utils.js'); const emptyUrl = ''; const analyticsType = 'endpoint'; @@ -42,18 +42,18 @@ var sharethroughAdapter = Object.assign(adapter( fireLoseBeacon(winningBidderCode, winningCPM, arid, type) { let loseBeaconUrl = this.STR_BEACON_HOST; - loseBeaconUrl = utils.tryAppendQueryString(loseBeaconUrl, 'winnerBidderCode', winningBidderCode); - loseBeaconUrl = utils.tryAppendQueryString(loseBeaconUrl, 'winnerCpm', winningCPM); - loseBeaconUrl = utils.tryAppendQueryString(loseBeaconUrl, 'arid', arid); - loseBeaconUrl = utils.tryAppendQueryString(loseBeaconUrl, 'type', type); + loseBeaconUrl = tryAppendQueryString(loseBeaconUrl, 'winnerBidderCode', winningBidderCode); + loseBeaconUrl = tryAppendQueryString(loseBeaconUrl, 'winnerCpm', winningCPM); + loseBeaconUrl = tryAppendQueryString(loseBeaconUrl, 'arid', arid); + loseBeaconUrl = tryAppendQueryString(loseBeaconUrl, 'type', type); loseBeaconUrl = this.appendEnvFields(loseBeaconUrl); this.fireBeacon(loseBeaconUrl); }, appendEnvFields(url) { - url = utils.tryAppendQueryString(url, 'hbVersion', '$prebid.version$'); - url = utils.tryAppendQueryString(url, 'strVersion', STR_VERSION); - url = utils.tryAppendQueryString(url, 'hbSource', 'prebid'); + url = tryAppendQueryString(url, 'hbVersion', '$prebid.version$'); + url = tryAppendQueryString(url, 'strVersion', STR_VERSION); + url = tryAppendQueryString(url, 'hbSource', 'prebid'); return url; }, diff --git a/modules/sharethroughBidAdapter.js b/modules/sharethroughBidAdapter.js index 3b4f0ec2a4e..11e62553038 100644 --- a/modules/sharethroughBidAdapter.js +++ b/modules/sharethroughBidAdapter.js @@ -1,5 +1,5 @@ +import { generateUUID, deepAccess, inIframe } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { createEidsArray } from './userId/eids.js'; @@ -29,7 +29,7 @@ export const sharethroughAdapterSpec = { const secure = nonHttp || (sharethroughInternal.getProtocol().indexOf('https') > -1); const req = { - id: utils.generateUUID(), + id: generateUUID(), at: 1, cur: ['USD'], tmax: timeout, @@ -82,7 +82,7 @@ export const sharethroughAdapterSpec = { const imps = bidRequests.map(bidReq => { const impression = {}; - const gpid = utils.deepAccess(bidReq, 'ortb2Imp.ext.data.pbadslot'); + const gpid = deepAccess(bidReq, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { impression.ext = { gpid: gpid }; } @@ -104,7 +104,7 @@ export const sharethroughAdapterSpec = { impression.video = { pos: nullish(videoRequest.pos, 0), - topframe: utils.inIframe() ? 0 : 1, + topframe: inIframe() ? 0 : 1, skip: nullish(videoRequest.skip, 0), linearity: nullish(videoRequest.linearity, 1), minduration: nullish(videoRequest.minduration, 5), @@ -126,8 +126,8 @@ export const sharethroughAdapterSpec = { if (videoRequest.companionad) impression.video.companionad = videoRequest.companionad; } else { impression.banner = { - pos: utils.deepAccess(bidReq, 'mediaTypes.banner.pos', 0), - topframe: utils.inIframe() ? 0 : 1, + pos: deepAccess(bidReq, 'mediaTypes.banner.pos', 0), + topframe: inIframe() ? 0 : 1, format: bidReq.sizes.map(size => ({ w: +size[0], h: +size[1] })), }; } @@ -252,9 +252,9 @@ function getBidRequestFloor(bid) { } function userIdAsEids(bidRequest) { - const eids = createEidsArray(utils.deepAccess(bidRequest, 'userId')) || []; + const eids = createEidsArray(deepAccess(bidRequest, 'userId')) || []; - const flocData = utils.deepAccess(bidRequest, 'userId.flocId'); + const flocData = deepAccess(bidRequest, 'userId.flocId'); const isFlocIdValid = flocData && flocData.id && flocData.version; if (isFlocIdValid) { eids.push({ diff --git a/modules/showheroes-bsBidAdapter.js b/modules/showheroes-bsBidAdapter.js index 8d94a8e508b..99378b494df 100644 --- a/modules/showheroes-bsBidAdapter.js +++ b/modules/showheroes-bsBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, getBidIdParameter, getWindowTop, logError } from '../src/utils.js'; import { config } from '../src/config.js'; import { Renderer } from '../src/Renderer.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; @@ -32,18 +32,18 @@ export const spec = { let adUnits = []; const pageURL = validBidRequests[0].params.contentPageUrl || bidderRequest.refererInfo.referer; const isStage = !!validBidRequests[0].params.stage; - const isOutstream = utils.deepAccess(validBidRequests[0], 'mediaTypes.video.context') === 'outstream'; - const isCustomRender = utils.deepAccess(validBidRequests[0], 'params.outstreamOptions.customRender'); - const isNodeRender = utils.deepAccess(validBidRequests[0], 'params.outstreamOptions.slot') || utils.deepAccess(validBidRequests[0], 'params.outstreamOptions.iframe'); - const isNativeRender = utils.deepAccess(validBidRequests[0], 'renderer'); - const outstreamOptions = utils.deepAccess(validBidRequests[0], 'params.outstreamOptions'); + const isOutstream = deepAccess(validBidRequests[0], 'mediaTypes.video.context') === 'outstream'; + const isCustomRender = deepAccess(validBidRequests[0], 'params.outstreamOptions.customRender'); + const isNodeRender = deepAccess(validBidRequests[0], 'params.outstreamOptions.slot') || deepAccess(validBidRequests[0], 'params.outstreamOptions.iframe'); + const isNativeRender = deepAccess(validBidRequests[0], 'renderer'); + const outstreamOptions = deepAccess(validBidRequests[0], 'params.outstreamOptions'); const isBanner = !!validBidRequests[0].mediaTypes.banner || (isOutstream && !(isCustomRender || isNativeRender || isNodeRender)); const defaultSchain = validBidRequests[0].schain || {}; validBidRequests.forEach((bid) => { const videoSizes = getVideoSizes(bid); const bannerSizes = getBannerSizes(bid); - const vpaidMode = utils.getBidIdParameter('vpaidMode', bid.params); + const vpaidMode = getBidIdParameter('vpaidMode', bid.params); const makeBids = (type, size) => { let context = ''; @@ -52,7 +52,7 @@ export const spec = { if (type === BANNER) { streamType = 5; } else { - context = utils.deepAccess(bid, 'mediaTypes.video.context'); + context = deepAccess(bid, 'mediaTypes.video.context'); if (vpaidMode && context === 'instream') { streamType = 1; } @@ -66,7 +66,7 @@ export const spec = { bidId: bid.bidId, mediaType: type, context: context, - playerId: utils.getBidIdParameter('playerId', bid.params), + playerId: getBidIdParameter('playerId', bid.params), auctionId: bidderRequest.auctionId, bidderCode: BIDDER_CODE, gdprConsent: bidderRequest.gdprConsent, @@ -100,7 +100,7 @@ export const spec = { 'adapterVersion': 2, 'pageURL': encodeURIComponent(pageURL), 'vastCacheEnabled': (!!config.getConfig('cache') && !isBanner && !outstreamOptions) || false, - 'isDesktop': utils.getWindowTop().document.documentElement.clientWidth > 700, + 'isDesktop': getWindowTop().document.documentElement.clientWidth > 700, 'xmlAndTag': !!(isOutstream && isCustomRender) || false, 'stage': isStage || undefined }, @@ -192,9 +192,9 @@ function createBids(bidRes, reqData) { vastXml: bid.vastXml, debug: reqData.debug, isStage: !!reqData.meta.stage, - customRender: utils.getBidIdParameter('customRender', currentBidParams.outstreamOptions), - slot: utils.getBidIdParameter('slot', currentBidParams.outstreamOptions), - iframe: utils.getBidIdParameter('iframe', currentBidParams.outstreamOptions), + customRender: getBidIdParameter('customRender', currentBidParams.outstreamOptions), + slot: getBidIdParameter('slot', currentBidParams.outstreamOptions), + iframe: getBidIdParameter('iframe', currentBidParams.outstreamOptions), } }); renderer.setRender(outstreamRender); @@ -212,7 +212,7 @@ function outstreamRender(bid) { bid.renderer.config.customRender(bid, embedCode); } else { try { - const inIframe = utils.getBidIdParameter('iframe', bid.renderer.config); + const inIframe = getBidIdParameter('iframe', bid.renderer.config); if (inIframe && window.document.getElementById(inIframe).nodeName === 'IFRAME') { const iframe = window.document.getElementById(inIframe); let framedoc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document); @@ -220,20 +220,20 @@ function outstreamRender(bid) { return; } - const slot = utils.getBidIdParameter('slot', bid.renderer.config) || bid.adUnitCode; + const slot = getBidIdParameter('slot', bid.renderer.config) || bid.adUnitCode; if (slot && window.document.getElementById(slot)) { window.document.getElementById(slot).appendChild(embedCode); } else if (slot) { - utils.logError('[ShowHeroes][renderer] Error: spot not found'); + logError('[ShowHeroes][renderer] Error: spot not found'); } } catch (err) { - utils.logError('[ShowHeroes][renderer] Error:' + err.message) + logError('[ShowHeroes][renderer] Error:' + err.message) } } } function createOutstreamEmbedCode(bid) { - const isStage = utils.getBidIdParameter('isStage', bid.renderer.config); + const isStage = getBidIdParameter('isStage', bid.renderer.config); const urls = getEnvURLs(isStage); const fragment = window.document.createDocumentFragment(); @@ -245,9 +245,9 @@ function createOutstreamEmbedCode(bid) { const spot = window.document.createElement('div'); spot.setAttribute('class', 'showheroes-spot'); - spot.setAttribute('data-player', utils.getBidIdParameter('playerId', bid.renderer.config)); - spot.setAttribute('data-debug', utils.getBidIdParameter('debug', bid.renderer.config)); - spot.setAttribute('data-ad-vast-tag', utils.getBidIdParameter('vastUrl', bid.renderer.config)); + spot.setAttribute('data-player', getBidIdParameter('playerId', bid.renderer.config)); + spot.setAttribute('data-debug', getBidIdParameter('debug', bid.renderer.config)); + spot.setAttribute('data-ad-vast-tag', getBidIdParameter('vastUrl', bid.renderer.config)); spot.setAttribute('data-stream-type', 'outstream'); fragment.appendChild(spot); @@ -275,11 +275,11 @@ function getBannerHtml (bid, reqBid, reqData) { } function getVideoSizes(bidRequest) { - return formatSizes(utils.deepAccess(bidRequest, 'mediaTypes.video.playerSize') || []); + return formatSizes(deepAccess(bidRequest, 'mediaTypes.video.playerSize') || []); } function getBannerSizes(bidRequest) { - return formatSizes(utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes') || []); + return formatSizes(deepAccess(bidRequest, 'mediaTypes.banner.sizes') || []); } function formatSizes(sizes) { diff --git a/modules/sigmoidAnalyticsAdapter.js b/modules/sigmoidAnalyticsAdapter.js index 303fbbc8995..da0ca9e38e5 100644 --- a/modules/sigmoidAnalyticsAdapter.js +++ b/modules/sigmoidAnalyticsAdapter.js @@ -5,11 +5,10 @@ import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; import { getStorageManager } from '../src/storageManager.js'; +import { generateUUID, logInfo, logError } from '../src/utils.js'; const storage = getStorageManager(); -const utils = require('../src/utils.js'); - const url = 'https://kinesis.us-east-1.amazonaws.com/'; const analyticsType = 'endpoint'; @@ -56,7 +55,7 @@ function buildSessionIdTimeoutLocalStorageKey() { function updateSessionId() { if (isSessionIdTimeoutExpired()) { - let newSessionId = utils.generateUUID(); + let newSessionId = generateUUID(); storage.setDataInLocalStorage(buildSessionIdLocalStorageKey(), newSessionId); } initOptions.sessionId = getSessionId(); @@ -206,7 +205,7 @@ sigmoidAdapter.originEnableAnalytics = sigmoidAdapter.enableAnalytics; sigmoidAdapter.enableAnalytics = function (config) { initOptions = config.options; initOptions.utmTagData = this.buildUtmTagData(); - utils.logInfo('Sigmoid Analytics enabled with config', initOptions); + logInfo('Sigmoid Analytics enabled with config', initOptions); sigmoidAdapter.originEnableAnalytics(config); }; @@ -246,7 +245,7 @@ function send(eventType, data, sendDataType) { AWS.config.credentials.get(function(err) { // attach event listener if (err) { - utils.logError(err); + logError(err); return; } // create kinesis service object diff --git a/modules/sirdataRtdProvider.js b/modules/sirdataRtdProvider.js index 373468b2f14..344357bcb62 100644 --- a/modules/sirdataRtdProvider.js +++ b/modules/sirdataRtdProvider.js @@ -7,7 +7,7 @@ * @requires module:modules/realTimeData */ import {getGlobal} from '../src/prebidGlobal.js'; -import * as utils from '../src/utils.js'; +import { deepAccess, logError, deepEqual, deepSetValue, isEmpty, mergeDeep } from '../src/utils.js'; import {submodule} from '../src/hook.js'; import {ajax} from '../src/ajax.js'; import findIndex from 'core-js-pure/features/array/find-index.js'; @@ -44,7 +44,7 @@ export function getSegmentsAndCategories(reqBidsConfigObj, onDone, moduleConfig, } // default global endpoint is cookie-based if no rules falls into cookieless or consent has been given or GDPR doesn't apply - if (!sirdataDomain || !gdprApplies || (utils.deepAccess(userConsent, 'gdpr.vendorData.vendor.consents') && userConsent.gdpr.vendorData.vendor.consents[53] && userConsent.gdpr.vendorData.purpose.consents[1] && userConsent.gdpr.vendorData.purpose.consents[4])) { + if (!sirdataDomain || !gdprApplies || (deepAccess(userConsent, 'gdpr.vendorData.vendor.consents') && userConsent.gdpr.vendorData.vendor.consents[53] && userConsent.gdpr.vendorData.purpose.consents[1] && userConsent.gdpr.vendorData.purpose.consents[4])) { sirdataDomain = 'sddan.com'; sendWithCredentials = true; } @@ -64,7 +64,7 @@ export function getSegmentsAndCategories(reqBidsConfigObj, onDone, moduleConfig, } } catch (e) { onDone(); - utils.logError('unable to parse Sirdata data' + e); + logError('unable to parse Sirdata data' + e); } } else if (req.status === 204) { onDone(); @@ -72,7 +72,7 @@ export function getSegmentsAndCategories(reqBidsConfigObj, onDone, moduleConfig, }, error: function () { onDone(); - utils.logError('unable to get Sirdata data'); + logError('unable to get Sirdata data'); } }, null, @@ -89,18 +89,18 @@ export function setGlobalOrtb2(segments, categories) { try { let addOrtb2 = {}; let testGlobal = getGlobal().getConfig('ortb2') || {}; - if (!utils.deepAccess(testGlobal, 'user.ext.data.sd_rtd') || !utils.deepEqual(testGlobal.user.ext.data.sd_rtd, segments)) { - utils.deepSetValue(addOrtb2, 'user.ext.data.sd_rtd', segments || {}); + if (!deepAccess(testGlobal, 'user.ext.data.sd_rtd') || !deepEqual(testGlobal.user.ext.data.sd_rtd, segments)) { + deepSetValue(addOrtb2, 'user.ext.data.sd_rtd', segments || {}); } - if (!utils.deepAccess(testGlobal, 'site.ext.data.sd_rtd') || !utils.deepEqual(testGlobal.site.ext.data.sd_rtd, categories)) { - utils.deepSetValue(addOrtb2, 'site.ext.data.sd_rtd', categories || {}); + if (!deepAccess(testGlobal, 'site.ext.data.sd_rtd') || !deepEqual(testGlobal.site.ext.data.sd_rtd, categories)) { + deepSetValue(addOrtb2, 'site.ext.data.sd_rtd', categories || {}); } - if (!utils.isEmpty(addOrtb2)) { - let ortb2 = {ortb2: utils.mergeDeep({}, testGlobal, addOrtb2)}; + if (!isEmpty(addOrtb2)) { + let ortb2 = {ortb2: mergeDeep({}, testGlobal, addOrtb2)}; getGlobal().setConfig(ortb2); } } catch (e) { - utils.logError(e) + logError(e) } return true; @@ -109,19 +109,19 @@ export function setGlobalOrtb2(segments, categories) { export function setBidderOrtb2(bidder, segments, categories) { try { let addOrtb2 = {}; - let testBidder = utils.deepAccess(config.getBidderConfig(), bidder + '.ortb2') || {}; - if (!utils.deepAccess(testBidder, 'user.ext.data.sd_rtd') || !utils.deepEqual(testBidder.user.ext.data.sd_rtd, segments)) { - utils.deepSetValue(addOrtb2, 'user.ext.data.sd_rtd', segments || {}); + let testBidder = deepAccess(config.getBidderConfig(), bidder + '.ortb2') || {}; + if (!deepAccess(testBidder, 'user.ext.data.sd_rtd') || !deepEqual(testBidder.user.ext.data.sd_rtd, segments)) { + deepSetValue(addOrtb2, 'user.ext.data.sd_rtd', segments || {}); } - if (!utils.deepAccess(testBidder, 'site.ext.data.sd_rtd') || !utils.deepEqual(testBidder.site.ext.data.sd_rtd, categories)) { - utils.deepSetValue(addOrtb2, 'site.ext.data.sd_rtd', categories || {}); + if (!deepAccess(testBidder, 'site.ext.data.sd_rtd') || !deepEqual(testBidder.site.ext.data.sd_rtd, categories)) { + deepSetValue(addOrtb2, 'site.ext.data.sd_rtd', categories || {}); } - if (!utils.isEmpty(addOrtb2)) { - let ortb2 = {ortb2: utils.mergeDeep({}, testBidder, addOrtb2)}; + if (!isEmpty(addOrtb2)) { + let ortb2 = {ortb2: mergeDeep({}, testBidder, addOrtb2)}; getGlobal().setBidderConfig({ bidders: [bidder], config: ortb2 }); } } catch (e) { - utils.logError(e) + logError(e) } return true; @@ -132,7 +132,7 @@ export function loadCustomFunction (todo, adUnit, list, data, bid) { if (typeof todo == 'function') { todo(adUnit, list, data, bid); } - } catch (e) { utils.logError(e); } + } catch (e) { logError(e); } return true; } @@ -148,14 +148,14 @@ export function getSegAndCatsArray(data, minScore) { } } } - } catch (e) { utils.logError(e); } + } catch (e) { logError(e); } try { if (data && data.segments) { for (let segId in data.segments) { sirdataData.segments.push(data.segments[segId].toString()); } } - } catch (e) { utils.logError(e); } + } catch (e) { logError(e); } return sirdataData; } @@ -165,7 +165,7 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { const globalMinScore = moduleConfig.params.hasOwnProperty('contextualMinRelevancyScore') ? moduleConfig.params.contextualMinRelevancyScore : 30; var sirdataData = getSegAndCatsArray(data, globalMinScore); - if (!sirdataData || (sirdataData.segments.length < 1 && sirdataData.categories.length < 1)) { utils.logError('no cats'); onDone(); return adUnits; } + if (!sirdataData || (sirdataData.segments.length < 1 && sirdataData.categories.length < 1)) { logError('no cats'); onDone(); return adUnits; } const sirdataList = sirdataData.segments.concat(sirdataData.categories); @@ -191,7 +191,7 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { n.setTargeting('sd_rtd', sirdataList.concat(curationData.segments).concat(curationData.categories)); } }) - } catch (e) { utils.logError(e); } + } catch (e) { logError(e); } } // Bid targeting level for FPD non-generic biders @@ -199,8 +199,8 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { var indexFound = false; adUnits.forEach(adUnit => { - if (!biddersParamsExist && !utils.deepAccess(adUnit, 'ortb2Imp.ext.data.sd_rtd')) { - utils.deepSetValue(adUnit, 'ortb2Imp.ext.data.sd_rtd', sirdataList); + if (!biddersParamsExist && !deepAccess(adUnit, 'ortb2Imp.ext.data.sd_rtd')) { + deepSetValue(adUnit, 'ortb2Imp.ext.data.sd_rtd', sirdataList); } adUnit.hasOwnProperty('bids') && adUnit.bids.forEach(bid => { @@ -236,7 +236,7 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { if (indexFound && moduleConfig.params.bidders[bidderIndex].hasOwnProperty('customFunction')) { loadCustomFunction(moduleConfig.params.bidders[bidderIndex].customFunction, adUnit, sirdataList.concat(curationData.segments).concat(curationData.categories), data, bid); } else { - utils.deepSetValue(bid, 'params.keywords.sd_rtd', sirdataList.concat(curationData.segments).concat(curationData.categories)); + deepSetValue(bid, 'params.keywords.sd_rtd', sirdataList.concat(curationData.segments).concat(curationData.categories)); } break; @@ -259,7 +259,7 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { target.push('sd_rtd=' + entry); } }); - utils.deepSetValue(bid, 'params.target', target.join(';')); + deepSetValue(bid, 'params.target', target.join(';')); } break; @@ -313,7 +313,7 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { if (indexFound && moduleConfig.params.bidders[bidderIndex].hasOwnProperty('customFunction')) { loadCustomFunction(moduleConfig.params.bidders[bidderIndex].customFunction, adUnit, sirdataList.concat(curationData.segments).concat(curationData.categories), data, bid); } else { - utils.deepSetValue(bid, 'ortb2.user.ext.data', {segments: sirdataData.segments.concat(curationData.segments), contextual_categories: {...data.contextual_categories, ...data.shared_taxonomy[curationId].contextual_categories}}); + deepSetValue(bid, 'ortb2.user.ext.data', {segments: sirdataData.segments.concat(curationData.segments), contextual_categories: {...data.contextual_categories, ...data.shared_taxonomy[curationId].contextual_categories}}); } break; @@ -372,16 +372,16 @@ export function addSegmentData(adUnits, data, moduleConfig, onDone) { default: if (!biddersParamsExist || indexFound) { - if (!utils.deepAccess(bid, 'ortb2.site.ext.data.sd_rtd')) { - utils.deepSetValue(bid, 'ortb2.site.ext.data.sd_rtd', sirdataData.categories); + if (!deepAccess(bid, 'ortb2.site.ext.data.sd_rtd')) { + deepSetValue(bid, 'ortb2.site.ext.data.sd_rtd', sirdataData.categories); } - if (!utils.deepAccess(bid, 'ortb2.user.ext.data.sd_rtd')) { - utils.deepSetValue(bid, 'ortb2.user.ext.data.sd_rtd', sirdataData.segments); + if (!deepAccess(bid, 'ortb2.user.ext.data.sd_rtd')) { + deepSetValue(bid, 'ortb2.user.ext.data.sd_rtd', sirdataData.segments); } } } } - } catch (e) { utils.logError(e) } + } catch (e) { logError(e) } }) }); diff --git a/modules/sizeMappingV2.js b/modules/sizeMappingV2.js index ffd242e57ac..95f0eea4075 100644 --- a/modules/sizeMappingV2.js +++ b/modules/sizeMappingV2.js @@ -4,7 +4,7 @@ * rendering. Read full API documentation on Prebid.org, http://prebid.org/dev-docs/modules/sizeMappingV2.html */ -import * as utils from '../src/utils.js'; +import { isArray, logError, isArrayOfNums, deepClone, logWarn, getWindowTop, deepEqual, logInfo, isValidMediaTypes, deepAccess, getDefinedParams, getUniqueIdentifierStr, flatten } from '../src/utils.js'; import { processNativeAdUnitParams } from '../src/native.js'; import { adunitCounter } from '../src/adUnits.js'; import includes from 'core-js-pure/features/array/includes.js'; @@ -66,7 +66,7 @@ export function isUsingNewSizeMapping(adUnits) { }); // checks for the presence of sizeConfig property at the adUnit.bids[].bidder object - adUnit.bids && utils.isArray(adUnit.bids) && adUnit.bids.forEach(bidder => { + adUnit.bids && isArray(adUnit.bids) && adUnit.bids.forEach(bidder => { if (bidder.sizeConfig) { if (isUsingSizeMappingBool === false) { isUsingSizeMappingBool = true; @@ -108,7 +108,7 @@ export function checkAdUnitSetupHook(adUnits) { If they do not, return 'false'. */ if (!(includes(keys, 'minViewPort') && includes(keys, propertyName))) { - utils.logError(`Ad unit ${adUnitCode}: Missing required property 'minViewPort' or 'sizes' from 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); + logError(`Ad unit ${adUnitCode}: Missing required property 'minViewPort' or 'sizes' from 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); isValid = false; return; } @@ -117,8 +117,8 @@ export function checkAdUnitSetupHook(adUnits) { Verify that 'config.minViewPort' property is in [width, height] format. If not, return false. */ - if (!utils.isArrayOfNums(config.minViewPort, 2)) { - utils.logError(`Ad unit ${adUnitCode}: Invalid declaration of 'minViewPort' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); + if (!isArrayOfNums(config.minViewPort, 2)) { + logError(`Ad unit ${adUnitCode}: Invalid declaration of 'minViewPort' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); isValid = false return; } @@ -141,7 +141,7 @@ export function checkAdUnitSetupHook(adUnits) { showError = true; } if (showError) { - utils.logError(`Ad unit ${adUnitCode}: Invalid declaration of '${propertyName}' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); + logError(`Ad unit ${adUnitCode}: Invalid declaration of '${propertyName}' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); return; } } @@ -152,13 +152,13 @@ export function checkAdUnitSetupHook(adUnits) { */ if (mediaType === 'native') { if (typeof config[propertyName] !== 'boolean') { - utils.logError(`Ad unit ${adUnitCode}: Invalid declaration of 'active' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); + logError(`Ad unit ${adUnitCode}: Invalid declaration of 'active' in 'mediaTypes.${mediaType}.sizeConfig[${index}]'. ${conditionalLogMessages[mediaType]}`); isValid = false; } } }); } else { - utils.logError(`Ad unit ${adUnitCode}: Invalid declaration of 'sizeConfig' in 'mediaTypes.${mediaType}.sizeConfig'. ${conditionalLogMessages[mediaType]}`); + logError(`Ad unit ${adUnitCode}: Invalid declaration of 'sizeConfig' in 'mediaTypes.${mediaType}.sizeConfig'. ${conditionalLogMessages[mediaType]}`); isValid = false; return isValid; } @@ -172,13 +172,13 @@ export function checkAdUnitSetupHook(adUnits) { const mediaTypes = adUnit.mediaTypes; 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; } if (mediaTypes.banner) { @@ -187,7 +187,7 @@ export function checkAdUnitSetupHook(adUnits) { validatedBanner = adUnitSetupChecks.validateBannerMediaType(adUnit); } else if (mediaTypes.banner.sizeConfig) { // Ad unit is using the 'sizeConfig' property, 'mediaTypes.banner.sizeConfig'. Apply the new checks! - validatedBanner = utils.deepClone(adUnit); + validatedBanner = deepClone(adUnit); const isBannerValid = validateSizeConfig('banner', mediaTypes.banner.sizeConfig, adUnit.code); if (!isBannerValid) { delete validatedBanner.mediaTypes.banner; @@ -204,8 +204,8 @@ export function checkAdUnitSetupHook(adUnits) { } } else { // Ad unit is invalid since it's mediaType property does not have either 'sizes' or 'sizeConfig' declared. - utils.logError(`Ad unit ${adUnit.code}: 'mediaTypes.banner' does not contain either 'sizes' or 'sizeConfig' property. Removing 'mediaTypes.banner' from ad unit.`); - validatedBanner = utils.deepClone(adUnit); + logError(`Ad unit ${adUnit.code}: 'mediaTypes.banner' does not contain either 'sizes' or 'sizeConfig' property. Removing 'mediaTypes.banner' from ad unit.`); + validatedBanner = deepClone(adUnit); delete validatedBanner.mediaTypes.banner; } } @@ -216,7 +216,7 @@ export function checkAdUnitSetupHook(adUnits) { validatedVideo = validatedBanner ? adUnitSetupChecks.validateVideoMediaType(validatedBanner) : adUnitSetupChecks.validateVideoMediaType(adUnit); } else if (mediaTypes.video.sizeConfig) { // Ad unit is using the 'sizeConfig' property, 'mediaTypes.video.sizeConfig'. Apply the new checks! - validatedVideo = validatedBanner || utils.deepClone(adUnit); + validatedVideo = validatedBanner || deepClone(adUnit); const isVideoValid = validateSizeConfig('video', mediaTypes.video.sizeConfig, adUnit.code); if (!isVideoValid) { delete validatedVideo.mediaTypes.video.sizeConfig; @@ -274,7 +274,7 @@ export function checkBidderSizeConfigFormat(sizeConfig) { const keys = Object.keys(config); if ((includes(keys, 'minViewPort') && includes(keys, 'relevantMediaTypes')) && - utils.isArrayOfNums(config.minViewPort, 2) && + isArrayOfNums(config.minViewPort, 2) && Array.isArray(config.relevantMediaTypes) && config.relevantMediaTypes.length > 0 && (config.relevantMediaTypes.length > 1 ? (config.relevantMediaTypes.every(mt => (includes(['banner', 'video', 'native'], mt)))) @@ -322,14 +322,14 @@ export function isLabelActivated(bidOrAdUnit, activeLabels, adUnitCode, adUnitIn let labelOperator; const labelsFound = Object.keys(bidOrAdUnit).filter(prop => prop === 'labelAny' || prop === 'labelAll'); if (labelsFound && labelsFound.length > 1) { - utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) + logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has multiple label operators. Using the first declared operator: ${labelsFound[0]}`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Bidder has multiple label operators. Using the first declared operator: ${labelsFound[0]}`)}`); } labelOperator = labelsFound[0]; if (labelOperator && !activeLabels) { - utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) + logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Found '${labelOperator}' on ad unit, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Found '${labelOperator}' on bidder, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`)}`); return true; @@ -337,13 +337,13 @@ export function isLabelActivated(bidOrAdUnit, activeLabels, adUnitCode, adUnitIn if (labelOperator === 'labelAll' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAll.length === 0) { - utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAll' with an empty array.`); + logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAll' with an empty array.`); return true; } return bidOrAdUnit.labelAll.every(label => includes(activeLabels, label)); } else if (labelOperator === 'labelAny' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAny.length === 0) { - utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAny' with an empty array.`); + logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAny' with an empty array.`); return true; } return bidOrAdUnit.labelAny.some(label => includes(activeLabels, label)); @@ -363,7 +363,7 @@ export function getFilteredMediaTypes(mediaTypes) { activeViewportHeight, transformedMediaTypes; - transformedMediaTypes = utils.deepClone(mediaTypes); + transformedMediaTypes = deepClone(mediaTypes); let activeSizeBucket = { banner: undefined, @@ -372,10 +372,10 @@ export function getFilteredMediaTypes(mediaTypes) { } try { - activeViewportWidth = utils.getWindowTop().innerWidth; - activeViewportHeight = utils.getWindowTop().innerHeight; + activeViewportWidth = getWindowTop().innerWidth; + activeViewportHeight = getWindowTop().innerHeight; } catch (e) { - utils.logWarn(`SizeMappingv2:: Unfriendly iframe blocks viewport size to be evaluated correctly`); + logWarn(`SizeMappingv2:: Unfriendly iframe blocks viewport size to be evaluated correctly`); activeViewportWidth = window.innerWidth; activeViewportHeight = window.innerHeight; } @@ -490,7 +490,7 @@ export function getAdUnitDetail(auctionId, adUnit, labels) { const adUnitsForAuction = sizeMappingInternalStore.getAuctionDetail(auctionId).adUnits; // check if the adUnit exists already in the sizeMappingInterStore (check for equivalence of 'code' && 'mediaTypes' properties) - const adUnitDetail = adUnitsForAuction.filter(adUnitDetail => adUnitDetail.adUnitCode === adUnit.code && utils.deepEqual(adUnitDetail.mediaTypes, adUnit.mediaTypes)); + const adUnitDetail = adUnitsForAuction.filter(adUnitDetail => adUnitDetail.adUnitCode === adUnit.code && deepEqual(adUnitDetail.mediaTypes, adUnit.mediaTypes)); if (adUnitDetail.length > 0) { adUnitDetail[0].cacheHits++; @@ -514,7 +514,7 @@ export function getAdUnitDetail(auctionId, adUnit, labels) { // set adUnitDetail in sizeMappingInternalStore against the correct 'auctionId'. sizeMappingInternalStore.setAuctionDetail(auctionId, adUnitDetail); - isLabelActivated && utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Active size buckets after filtration: `, sizeBucketToSizeMap); + isLabelActivated && logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Active size buckets after filtration: `, sizeBucketToSizeMap); return adUnitDetail; } @@ -522,13 +522,13 @@ export function getAdUnitDetail(auctionId, adUnit, labels) { export function getBids({ bidderCode, auctionId, bidderRequestId, adUnits, labels, src }) { return adUnits.reduce((result, adUnit) => { - if (adUnit.mediaTypes && utils.isValidMediaTypes(adUnit.mediaTypes)) { + if (adUnit.mediaTypes && isValidMediaTypes(adUnit.mediaTypes)) { const { activeViewport, transformedMediaTypes, instance: adUnitInstance, isLabelActivated, cacheHits } = internal.getAdUnitDetail(auctionId, adUnit, labels); if (isLabelActivated) { // check if adUnit has any active media types remaining, if not drop the adUnit from auction, // else proceed to evaluate the bids object. if (Object.keys(transformedMediaTypes).length === 0) { - cacheHits === 0 && utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Ad unit disabled since there are no active media types after sizeConfig filtration.`); + cacheHits === 0 && logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Ad unit disabled since there are no active media types after sizeConfig filtration.`); return result; } result @@ -536,19 +536,19 @@ export function getBids({ bidderCode, auctionId, bidderRequestId, adUnits, label .reduce((bids, bid) => { if (internal.isLabelActivated(bid, labels, adUnit.code, adUnitInstance)) { // handle native params - const nativeParams = adUnit.nativeParams || utils.deepAccess(adUnit, 'mediaTypes.native'); + const nativeParams = adUnit.nativeParams || deepAccess(adUnit, 'mediaTypes.native'); if (nativeParams) { bid = Object.assign({}, bid, { nativeParams: processNativeAdUnitParams(nativeParams) }); } - bid = Object.assign({}, bid, utils.getDefinedParams(adUnit, ['mediaType', 'renderer'])); + bid = Object.assign({}, bid, getDefinedParams(adUnit, ['mediaType', 'renderer'])); if (bid.sizeConfig) { const relevantMediaTypes = internal.getRelevantMediaTypesForBidder(bid.sizeConfig, activeViewport); if (relevantMediaTypes.length === 0) { - utils.logError(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bidderCode} => 'sizeConfig' is not configured properly. This bidder won't be eligible for sizeConfig checks and will remail active.`); + logError(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bidderCode} => 'sizeConfig' is not configured properly. This bidder won't be eligible for sizeConfig checks and will remail active.`); bid = Object.assign({}, bid); } else if (relevantMediaTypes[0] !== 'none') { const bidderMediaTypes = Object @@ -562,20 +562,20 @@ export function getBids({ bidderCode, auctionId, bidderRequestId, adUnits, label if (Object.keys(bidderMediaTypes).length > 0) { bid = Object.assign({}, bid, { mediaTypes: bidderMediaTypes }); } else { - utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => 'relevantMediaTypes' does not match with any of the active mediaTypes at the Ad Unit level. This bidder is disabled.`); + logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => 'relevantMediaTypes' does not match with any of the active mediaTypes at the Ad Unit level. This bidder is disabled.`); return bids; } } else { - utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => 'relevantMediaTypes' is set to 'none' in sizeConfig for current viewport size. This bidder is disabled.`); + logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => 'relevantMediaTypes' is set to 'none' in sizeConfig for current viewport size. This bidder is disabled.`); return bids; } } bids.push(Object.assign({}, bid, { adUnitCode: adUnit.code, transactionId: adUnit.transactionId, - sizes: utils.deepAccess(transformedMediaTypes, 'banner.sizes') || utils.deepAccess(transformedMediaTypes, 'video.playerSize') || [], + sizes: deepAccess(transformedMediaTypes, 'banner.sizes') || deepAccess(transformedMediaTypes, 'video.playerSize') || [], mediaTypes: bid.mediaTypes || transformedMediaTypes, - bidId: bid.bid_id || utils.getUniqueIdentifierStr(), + bidId: bid.bid_id || getUniqueIdentifierStr(), bidderRequestId, auctionId, src, @@ -585,17 +585,17 @@ export function getBids({ bidderCode, auctionId, bidderRequestId, adUnits, label })); return bids; } else { - utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => Label check for this bidder has failed. This bidder is disabled.`); + logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}), Bidder: ${bid.bidder} => Label check for this bidder has failed. This bidder is disabled.`); return bids; } }, [])); } else { - cacheHits === 0 && utils.logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Ad unit is disabled due to failing label check.`); + cacheHits === 0 && logInfo(`Size Mapping V2:: Ad Unit: ${adUnit.code}(${adUnitInstance}) => Ad unit is disabled due to failing label check.`); } } else { - utils.logWarn(`Size Mapping V2:: Ad Unit: ${adUnit.code} => Ad unit has declared invalid 'mediaTypes' or has not declared a 'mediaTypes' property`); + logWarn(`Size Mapping V2:: Ad Unit: ${adUnit.code} => Ad unit has declared invalid 'mediaTypes' or has not declared a 'mediaTypes' property`); return result; } return result; - }, []).reduce(utils.flatten, []).filter(val => val !== ''); + }, []).reduce(flatten, []).filter(val => val !== ''); } diff --git a/modules/smaatoBidAdapter.js b/modules/smaatoBidAdapter.js index 700fcf17785..dd389b42098 100644 --- a/modules/smaatoBidAdapter.js +++ b/modules/smaatoBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, getDNT, deepSetValue, logInfo, logError, isEmpty, getAdUnitSizes, fill, chunk, getMaxValueFromArray, getMinValueFromArray } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {config} from '../src/config.js'; import {ADPOD, BANNER, VIDEO} from '../src/mediaTypes.js'; @@ -17,7 +17,7 @@ const buildOpenRtbBidRequest = (bidRequest, bidderRequest) => { site: { id: window.location.hostname, publisher: { - id: utils.deepAccess(bidRequest, 'params.publisherId') + id: deepAccess(bidRequest, 'params.publisherId') }, domain: window.location.hostname, page: window.location.href, @@ -26,7 +26,7 @@ const buildOpenRtbBidRequest = (bidRequest, bidderRequest) => { device: { language: (navigator && navigator.language) ? navigator.language.split('-')[0] : '', ua: navigator.userAgent, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, h: screen.height, w: screen.width }, @@ -47,34 +47,34 @@ const buildOpenRtbBidRequest = (bidRequest, bidderRequest) => { Object.assign(requestTemplate.site, ortb2.site); if (bidderRequest.gdprConsent && bidderRequest.gdprConsent.gdprApplies === true) { - utils.deepSetValue(requestTemplate, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies ? 1 : 0); - utils.deepSetValue(requestTemplate, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(requestTemplate, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies ? 1 : 0); + deepSetValue(requestTemplate, 'user.ext.consent', bidderRequest.gdprConsent.consentString); } if (bidderRequest.uspConsent !== undefined) { - utils.deepSetValue(requestTemplate, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(requestTemplate, 'regs.ext.us_privacy', bidderRequest.uspConsent); } - if (utils.deepAccess(bidRequest, 'params.app')) { - const geo = utils.deepAccess(bidRequest, 'params.app.geo'); - utils.deepSetValue(requestTemplate, 'device.geo', geo); - const ifa = utils.deepAccess(bidRequest, 'params.app.ifa') - utils.deepSetValue(requestTemplate, 'device.ifa', ifa); + if (deepAccess(bidRequest, 'params.app')) { + const geo = deepAccess(bidRequest, 'params.app.geo'); + deepSetValue(requestTemplate, 'device.geo', geo); + const ifa = deepAccess(bidRequest, 'params.app.ifa') + deepSetValue(requestTemplate, 'device.ifa', ifa); } - const eids = utils.deepAccess(bidRequest, 'userIdAsEids'); + const eids = deepAccess(bidRequest, 'userIdAsEids'); if (eids && eids.length) { - utils.deepSetValue(requestTemplate, 'user.ext.eids', eids); + deepSetValue(requestTemplate, 'user.ext.eids', eids); } let requests = []; - if (utils.deepAccess(bidRequest, 'mediaTypes.banner')) { + if (deepAccess(bidRequest, 'mediaTypes.banner')) { const bannerRequest = Object.assign({}, requestTemplate, createBannerImp(bidRequest)); requests.push(bannerRequest); } - const videoMediaType = utils.deepAccess(bidRequest, 'mediaTypes.video'); + const videoMediaType = deepAccess(bidRequest, 'mediaTypes.video'); if (videoMediaType) { if (videoMediaType.context === ADPOD) { const adPodRequest = Object.assign({}, requestTemplate, createAdPodImp(bidRequest, videoMediaType)); @@ -90,7 +90,7 @@ const buildOpenRtbBidRequest = (bidRequest, bidderRequest) => { } const buildServerRequest = (validBidRequest, data) => { - utils.logInfo('[SMAATO] OpenRTB Request:', data); + logInfo('[SMAATO] OpenRTB Request:', data); return { method: 'POST', url: validBidRequest.params.endpoint || SMAATO_ENDPOINT, @@ -114,47 +114,47 @@ export const spec = { */ isBidRequestValid: (bid) => { if (typeof bid.params !== 'object') { - utils.logError('[SMAATO] Missing params object'); + logError('[SMAATO] Missing params object'); return false; } if (typeof bid.params.publisherId !== 'string') { - utils.logError('[SMAATO] Missing mandatory publisherId param'); + logError('[SMAATO] Missing mandatory publisherId param'); return false; } - if (utils.deepAccess(bid, 'mediaTypes.video.context') === ADPOD) { - utils.logInfo('[SMAATO] Verifying adpod bid request'); + if (deepAccess(bid, 'mediaTypes.video.context') === ADPOD) { + logInfo('[SMAATO] Verifying adpod bid request'); if (typeof bid.params.adbreakId !== 'string') { - utils.logError('[SMAATO] Missing for adpod request mandatory adbreakId param'); + logError('[SMAATO] Missing for adpod request mandatory adbreakId param'); return false; } if (bid.params.adspaceId) { - utils.logError('[SMAATO] The adspaceId param is not allowed in an adpod bid request'); + logError('[SMAATO] The adspaceId param is not allowed in an adpod bid request'); return false; } } else { - utils.logInfo('[SMAATO] Verifying a non adpod bid request'); + logInfo('[SMAATO] Verifying a non adpod bid request'); if (typeof bid.params.adspaceId !== 'string') { - utils.logError('[SMAATO] Missing mandatory adspaceId param'); + logError('[SMAATO] Missing mandatory adspaceId param'); return false; } if (bid.params.adbreakId) { - utils.logError('[SMAATO] The adbreakId param is only allowed in an adpod bid request'); + logError('[SMAATO] The adbreakId param is only allowed in an adpod bid request'); return false; } } - utils.logInfo('[SMAATO] Verification done, all good'); + logInfo('[SMAATO] Verification done, all good'); return true; }, buildRequests: (validBidRequests, bidderRequest) => { - utils.logInfo('[SMAATO] Client version:', SMAATO_CLIENT); + logInfo('[SMAATO] Client version:', SMAATO_CLIENT); return validBidRequests.map((validBidRequest) => { const openRtbBidRequests = buildOpenRtbBidRequest(validBidRequest, bidderRequest); @@ -169,19 +169,19 @@ export const spec = { */ interpretResponse: (serverResponse, bidRequest) => { // response is empty (HTTP 204) - if (utils.isEmpty(serverResponse.body)) { - utils.logInfo('[SMAATO] Empty response body HTTP 204, no bids'); + if (isEmpty(serverResponse.body)) { + logInfo('[SMAATO] Empty response body HTTP 204, no bids'); return []; // no bids } const serverResponseHeaders = serverResponse.headers; const smtExpires = serverResponseHeaders.get('X-SMT-Expires'); - utils.logInfo('[SMAATO] Expires:', smtExpires); + logInfo('[SMAATO] Expires:', smtExpires); const ttlInSec = smtExpires ? Math.floor((smtExpires - Date.now()) / 1000) : 300; const response = serverResponse.body; - utils.logInfo('[SMAATO] OpenRTB Response:', response); + logInfo('[SMAATO] OpenRTB Response:', response); const smtAdType = serverResponseHeaders.get('X-SMT-ADTYPE'); const bids = []; @@ -195,7 +195,7 @@ export const spec = { ttl: ttlInSec, creativeId: bid.crid, dealId: bid.dealid || null, - netRevenue: utils.deepAccess(bid, 'ext.net', true), + netRevenue: deepAccess(bid, 'ext.net', true), currency: response.cur, meta: { advertiserDomains: bid.adomain, @@ -204,7 +204,7 @@ export const spec = { } }; - const videoContext = utils.deepAccess(JSON.parse(bidRequest.data).imp[0], 'video.ext.context') + const videoContext = deepAccess(JSON.parse(bidRequest.data).imp[0], 'video.ext.context') if (videoContext === ADPOD) { resultingBid.vastXml = bid.adm; resultingBid.mediaType = VIDEO; @@ -234,14 +234,14 @@ export const spec = { bids.push(resultingBid); break; default: - utils.logInfo('[SMAATO] Invalid ad type:', smtAdType); + logInfo('[SMAATO] Invalid ad type:', smtAdType); } } resultingBid.meta.mediaType = resultingBid.mediaType; }); }); - utils.logInfo('[SMAATO] Prebid bids:', bids); + logInfo('[SMAATO] Prebid bids:', bids); return bids; }, @@ -292,12 +292,12 @@ const createRichmediaAd = (adm) => { }; function createBannerImp(bidRequest) { - const adUnitSizes = utils.getAdUnitSizes(bidRequest); + const adUnitSizes = getAdUnitSizes(bidRequest); const sizes = adUnitSizes.map((size) => ({w: size[0], h: size[1]})); return { imp: [{ id: bidRequest.bidId, - tagid: utils.deepAccess(bidRequest, 'params.adspaceId'), + tagid: deepAccess(bidRequest, 'params.adspaceId'), bidfloor: getBidFloor(bidRequest, BANNER, adUnitSizes), banner: { w: sizes[0].w, @@ -312,7 +312,7 @@ function createVideoImp(bidRequest, videoMediaType) { return { imp: [{ id: bidRequest.bidId, - tagid: utils.deepAccess(bidRequest, 'params.adspaceId'), + tagid: deepAccess(bidRequest, 'params.adspaceId'), bidfloor: getBidFloor(bidRequest, VIDEO, videoMediaType.playerSize), video: { mimes: videoMediaType.mimes, @@ -335,7 +335,7 @@ function createVideoImp(bidRequest, videoMediaType) { } function createAdPodImp(bidRequest, videoMediaType) { - const tagid = utils.deepAccess(bidRequest, 'params.adbreakId') + const tagid = deepAccess(bidRequest, 'params.adbreakId') const bce = config.getConfig('adpod.brandCategoryExclusion') let imp = { id: bidRequest.bidId, @@ -359,13 +359,13 @@ function createAdPodImp(bidRequest, videoMediaType) { } const numberOfPlacements = getAdPodNumberOfPlacements(videoMediaType) - let imps = utils.fill(imp, numberOfPlacements) + let imps = fill(imp, numberOfPlacements) const durationRangeSec = videoMediaType.durationRangeSec if (videoMediaType.requireExactDuration) { // equal distribution of numberOfPlacement over all available durations const divider = Math.ceil(numberOfPlacements / durationRangeSec.length) - const chunked = utils.chunk(imps, divider) + const chunked = chunk(imps, divider) // each configured duration is set as min/maxduration for a subset of requests durationRangeSec.forEach((duration, index) => { @@ -378,7 +378,7 @@ function createAdPodImp(bidRequest, videoMediaType) { }); } else { // all maxdurations should be the same - const maxDuration = utils.getMaxValueFromArray(durationRangeSec); + const maxDuration = getMaxValueFromArray(durationRangeSec); imps.map((imp, index) => { const sequence = index + 1; imp.video.maxduration = maxDuration @@ -393,7 +393,7 @@ function createAdPodImp(bidRequest, videoMediaType) { function getAdPodNumberOfPlacements(videoMediaType) { const {adPodDurationSec, durationRangeSec, requireExactDuration} = videoMediaType - const minAllowedDuration = utils.getMinValueFromArray(durationRangeSec) + const minAllowedDuration = getMinValueFromArray(durationRangeSec) const numberOfPlacements = Math.floor(adPodDurationSec / minAllowedDuration) return requireExactDuration @@ -423,7 +423,7 @@ const addOptionalAdpodParameters = (request, videoMediaType) => { content.livestream = videoMediaType.contentMode === 'live' ? 1 : 0 } - if (!utils.isEmpty(content)) { + if (!isEmpty(content)) { request.site.content = content } } diff --git a/modules/smartadserverBidAdapter.js b/modules/smartadserverBidAdapter.js index a7b609bca20..d6e1c8de452 100644 --- a/modules/smartadserverBidAdapter.js +++ b/modules/smartadserverBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, deepClone, logError, isFn, isPlainObject } from '../src/utils.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; import { createEidsArray } from './userId/eids.js'; @@ -170,8 +170,8 @@ export const spec = { payload.us_privacy = bidderRequest.uspConsent; } - const videoMediaType = utils.deepAccess(bid, 'mediaTypes.video'); - const bannerMediaType = utils.deepAccess(bid, 'mediaTypes.banner'); + const videoMediaType = deepAccess(bid, 'mediaTypes.video'); + const bannerMediaType = deepAccess(bid, 'mediaTypes.banner'); const isAdUnitContainingVideo = videoMediaType && (videoMediaType.context === 'instream' || videoMediaType.context === 'outstream'); if (!isAdUnitContainingVideo && bannerMediaType) { payload.sizes = spec.adaptBannerSizes(bannerMediaType.sizes); @@ -182,7 +182,7 @@ export const spec = { } else if (isAdUnitContainingVideo && bannerMediaType) { // If there are video and banner media types in the ad unit, we clone the payload // to create a specific one for video. - let videoPayload = utils.deepClone(payload); + let videoPayload = deepClone(payload); spec.fillPayloadForVideoBidRequest(videoPayload, videoMediaType, bid.params.video); bidRequests.push(spec.createServerRequest(videoPayload, bid.params.domain)); @@ -238,7 +238,7 @@ export const spec = { bidResponses.push(bidResponse); } } catch (error) { - utils.logError('Error while parsing smart server response', error); + logError('Error while parsing smart server response', error); } return bidResponses; }, @@ -251,7 +251,7 @@ export const spec = { * @return {number} Floor price */ getBidFloor: function (bid, currency) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return DEFAULT_FLOOR; } @@ -261,7 +261,7 @@ export const spec = { size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor)) { + if (isPlainObject(floor) && !isNaN(floor.floor)) { return floor.floor; } diff --git a/modules/smartxBidAdapter.js b/modules/smartxBidAdapter.js index 73e036cadb0..da63331cd0f 100644 --- a/modules/smartxBidAdapter.js +++ b/modules/smartxBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logError, deepAccess, isArray, getBidIdParameter, getDNT, generateUUID, isEmpty, _each, logMessage, logWarn, isFn, isPlainObject } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; @@ -22,37 +22,37 @@ export const spec = { */ isBidRequestValid: function (bid) { if (bid && typeof bid.params !== 'object') { - utils.logError(BIDDER_CODE + ': params is not defined or is incorrect in the bidder settings.'); + logError(BIDDER_CODE + ': params is not defined or is incorrect in the bidder settings.'); return false; } - if (!utils.deepAccess(bid, 'mediaTypes.video')) { - utils.logError(BIDDER_CODE + ': mediaTypes.video is not present in the bidder settings.'); + if (!deepAccess(bid, 'mediaTypes.video')) { + logError(BIDDER_CODE + ': mediaTypes.video is not present in the bidder settings.'); return false; } - const playerSize = utils.deepAccess(bid, 'mediaTypes.video.playerSize'); - if (!playerSize || !utils.isArray(playerSize)) { - utils.logError(BIDDER_CODE + ': mediaTypes.video.playerSize is not defined in the bidder settings.'); + const playerSize = deepAccess(bid, 'mediaTypes.video.playerSize'); + if (!playerSize || !isArray(playerSize)) { + logError(BIDDER_CODE + ': mediaTypes.video.playerSize is not defined in the bidder settings.'); return false; } - if (!utils.getBidIdParameter('tagId', bid.params)) { - utils.logError(BIDDER_CODE + ': tagId is not present in bidder params'); + if (!getBidIdParameter('tagId', bid.params)) { + logError(BIDDER_CODE + ': tagId is not present in bidder params'); return false; } - if (!utils.getBidIdParameter('publisherId', bid.params)) { - utils.logError(BIDDER_CODE + ': publisherId is not present in bidder params'); + if (!getBidIdParameter('publisherId', bid.params)) { + logError(BIDDER_CODE + ': publisherId is not present in bidder params'); return false; } - if (!utils.getBidIdParameter('siteId', bid.params)) { - utils.logError(BIDDER_CODE + ': siteId is not present in bidder params'); + if (!getBidIdParameter('siteId', bid.params)) { + logError(BIDDER_CODE + ': siteId is not present in bidder params'); return false; } - if (utils.deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { - if (!utils.getBidIdParameter('outstream_options', bid.params)) { - utils.logError(BIDDER_CODE + ': outstream_options parameter is not defined'); + if (deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { + if (!getBidIdParameter('outstream_options', bid.params)) { + logError(BIDDER_CODE + ': outstream_options parameter is not defined'); return false; } - if (!utils.getBidIdParameter('slot', bid.params.outstream_options)) { - utils.logError(BIDDER_CODE + ': slot parameter is not defined in outstream_options object in the configuration'); + if (!getBidIdParameter('slot', bid.params.outstream_options)) { + logError(BIDDER_CODE + ': slot parameter is not defined in outstream_options object in the configuration'); return false; } } @@ -71,33 +71,33 @@ export const spec = { const isPageSecure = !!page.match(/^https:/) const smartxRequests = bidRequests.map(function (bid) { - const tagId = utils.getBidIdParameter('tagId', bid.params); - const publisherId = utils.getBidIdParameter('publisherId', bid.params); + const tagId = getBidIdParameter('tagId', bid.params); + const publisherId = getBidIdParameter('publisherId', bid.params); const bidfloor = getBidFloor(bid) || 0; - const bidfloorcur = utils.getBidIdParameter('bidfloorcur', bid.params) || 'EUR'; - const siteId = utils.getBidIdParameter('siteId', bid.params); - const domain = utils.getBidIdParameter('domain', bid.params); - const cat = utils.getBidIdParameter('cat', bid.params) || ['']; + const bidfloorcur = getBidIdParameter('bidfloorcur', bid.params) || 'EUR'; + const siteId = getBidIdParameter('siteId', bid.params); + const domain = getBidIdParameter('domain', bid.params); + const cat = getBidIdParameter('cat', bid.params) || ['']; let pubcid = null; - const playerSize = utils.deepAccess(bid, 'mediaTypes.video.playerSize'); + const playerSize = deepAccess(bid, 'mediaTypes.video.playerSize'); const contentWidth = playerSize[0][0]; const contentHeight = playerSize[0][1]; - const secure = +(isPageSecure || (utils.getBidIdParameter('secure', bid.params) ? 1 : 0)); + const secure = +(isPageSecure || (getBidIdParameter('secure', bid.params) ? 1 : 0)); const ext = { sdk_name: 'Prebid 1+' }; - const mimes = utils.getBidIdParameter('mimes', bid.params) || ['application/javascript', 'video/mp4', 'video/webm']; - const linearity = utils.getBidIdParameter('linearity', bid.params) || 1; - const minduration = utils.getBidIdParameter('minduration', bid.params) || 0; - const maxduration = utils.getBidIdParameter('maxduration', bid.params) || 500; - const startdelay = utils.getBidIdParameter('startdelay', bid.params) || 0; - const minbitrate = utils.getBidIdParameter('minbitrate', bid.params) || 0; - const maxbitrate = utils.getBidIdParameter('maxbitrate', bid.params) || 3500; - const delivery = utils.getBidIdParameter('delivery', bid.params) || [2]; - const pos = utils.getBidIdParameter('pos', bid.params) || 1; - const api = utils.getBidIdParameter('api', bid.params) || [2]; - const protocols = utils.getBidIdParameter('protocols', bid.params) || [2, 3, 5, 6]; - var contextcustom = utils.deepAccess(bid, 'mediaTypes.video.context'); + const mimes = getBidIdParameter('mimes', bid.params) || ['application/javascript', 'video/mp4', 'video/webm']; + const linearity = getBidIdParameter('linearity', bid.params) || 1; + const minduration = getBidIdParameter('minduration', bid.params) || 0; + const maxduration = getBidIdParameter('maxduration', bid.params) || 500; + const startdelay = getBidIdParameter('startdelay', bid.params) || 0; + const minbitrate = getBidIdParameter('minbitrate', bid.params) || 0; + const maxbitrate = getBidIdParameter('maxbitrate', bid.params) || 3500; + const delivery = getBidIdParameter('delivery', bid.params) || [2]; + const pos = getBidIdParameter('pos', bid.params) || 1; + const api = getBidIdParameter('api', bid.params) || [2]; + const protocols = getBidIdParameter('protocols', bid.params) || [2, 3, 5, 6]; + var contextcustom = deepAccess(bid, 'mediaTypes.video.context'); var placement = 1; if (contextcustom === 'outstream') { @@ -141,18 +141,18 @@ export const spec = { const device = { h: screen.height, w: screen.width, - dnt: utils.getDNT() ? 1 : 0, + dnt: getDNT() ? 1 : 0, language: navigator[language].split('-')[0], make: navigator.vendor ? navigator.vendor : '', ua: navigator.userAgent }; - const at = utils.getBidIdParameter('at', bid.params) || 2; + const at = getBidIdParameter('at', bid.params) || 2; - const cur = utils.getBidIdParameter('cur', bid.params) || ['EUR']; + const cur = getBidIdParameter('cur', bid.params) || ['EUR']; const requestPayload = { - id: utils.generateUUID(), + id: generateUUID(), imp: smartxReq, site: { id: siteId, @@ -188,14 +188,14 @@ export const spec = { } // Only add the user object if it's not empty - if (!utils.isEmpty(userExt)) { + if (!isEmpty(userExt)) { requestPayload.user = { ext: userExt }; } // Targeting - if (utils.getBidIdParameter('data', bid.params.user)) { + if (getBidIdParameter('data', bid.params.user)) { var targetingarr = []; for (var i = 0; i < bid.params.user.data.length; i++) { var isemq = (bid.params.user.data[i].name) || 'empty'; @@ -246,9 +246,9 @@ export const spec = { interpretResponse: function (serverResponse, bidderRequest) { const bidResponses = []; const serverResponseBody = serverResponse.body; - if (serverResponseBody && utils.isArray(serverResponseBody.seatbid)) { - utils._each(serverResponseBody.seatbid, function (bids) { - utils._each(bids.bid, function (smartxBid) { + if (serverResponseBody && isArray(serverResponseBody.seatbid)) { + _each(serverResponseBody.seatbid, function (bids) { + _each(bids.bid, function (smartxBid) { let currentBidRequest = {}; for (let i in bidderRequest.bidRequest.bids) { if (smartxBid.impid == bidderRequest.bidRequest.bids[i].bidId) { @@ -259,7 +259,7 @@ export const spec = { * Make sure currency and price are the right ones * TODO: what about the pre_market_bid partners sizes? */ - utils._each(currentBidRequest.params.pre_market_bids, function (pmb) { + _each(currentBidRequest.params.pre_market_bids, function (pmb) { if (pmb.deal_id == smartxBid.id) { smartxBid.price = pmb.price; serverResponseBody.cur = pmb.currency; @@ -285,10 +285,10 @@ export const spec = { bid.meta.advertiserDomains = smartxBid.adomain; } - const context = utils.deepAccess(currentBidRequest, 'mediaTypes.video.context'); + const context = deepAccess(currentBidRequest, 'mediaTypes.video.context'); if (context === 'outstream') { - const playersize = utils.deepAccess(currentBidRequest, 'mediaTypes.video.playerSize'); + const playersize = deepAccess(currentBidRequest, 'mediaTypes.video.playerSize'); const renderer = Renderer.install({ id: 0, url: 'https://dco.smartclip.net/?plc=7777778', @@ -296,27 +296,27 @@ export const spec = { adText: 'SmartX Outstream Video Ad via Prebid.js', player_width: playersize[0][0], player_height: playersize[0][1], - content_page_url: utils.deepAccess(bidderRequest, 'data.site.page'), - ad_mute: +!!utils.deepAccess(currentBidRequest, 'params.ad_mute'), - hide_skin: +!!utils.deepAccess(currentBidRequest, 'params.hide_skin'), - outstream_options: utils.deepAccess(currentBidRequest, 'params.outstream_options') + content_page_url: deepAccess(bidderRequest, 'data.site.page'), + ad_mute: +!!deepAccess(currentBidRequest, 'params.ad_mute'), + hide_skin: +!!deepAccess(currentBidRequest, 'params.hide_skin'), + outstream_options: deepAccess(currentBidRequest, 'params.outstream_options') } }); try { renderer.setRender(createOutstreamConfig); renderer.setEventHandlers({ impression: function impression() { - return utils.logMessage('SmartX outstream video impression event'); + return logMessage('SmartX outstream video impression event'); }, loaded: function loaded() { - return utils.logMessage('SmartX outstream video loaded event'); + return logMessage('SmartX outstream video loaded event'); }, ended: function ended() { - return utils.logMessage('SmartX outstream renderer video event'); + return logMessage('SmartX outstream renderer video event'); } }); } catch (err) { - utils.logWarn('Prebid Error calling setRender or setEventHandlers on renderer', err); + logWarn('Prebid Error calling setRender or setEventHandlers on renderer', err); } bid.renderer = renderer; } @@ -329,16 +329,16 @@ export const spec = { } function createOutstreamConfig(bid) { - let confMinAdWidth = utils.getBidIdParameter('minAdWidth', bid.renderer.config.outstream_options) || 290; - let confMaxAdWidth = utils.getBidIdParameter('maxAdWidth', bid.renderer.config.outstream_options) || 900; - let confStartOpen = utils.getBidIdParameter('startOpen', bid.renderer.config.outstream_options) - let confEndingScreen = utils.getBidIdParameter('endingScreen', bid.renderer.config.outstream_options) - let confTitle = utils.getBidIdParameter('title', bid.renderer.config.outstream_options); - let confSkipOffset = utils.getBidIdParameter('skipOffset', bid.renderer.config.outstream_options); - let confDesiredBitrate = utils.getBidIdParameter('desiredBitrate', bid.renderer.config.outstream_options); - let elementId = utils.getBidIdParameter('slot', bid.renderer.config.outstream_options) || bid.adUnitCode; + let confMinAdWidth = getBidIdParameter('minAdWidth', bid.renderer.config.outstream_options) || 290; + let confMaxAdWidth = getBidIdParameter('maxAdWidth', bid.renderer.config.outstream_options) || 900; + let confStartOpen = getBidIdParameter('startOpen', bid.renderer.config.outstream_options) + let confEndingScreen = getBidIdParameter('endingScreen', bid.renderer.config.outstream_options) + let confTitle = getBidIdParameter('title', bid.renderer.config.outstream_options); + let confSkipOffset = getBidIdParameter('skipOffset', bid.renderer.config.outstream_options); + let confDesiredBitrate = getBidIdParameter('desiredBitrate', bid.renderer.config.outstream_options); + let elementId = getBidIdParameter('slot', bid.renderer.config.outstream_options) || bid.adUnitCode; - utils.logMessage('[SMARTX][renderer] Handle SmartX outstream renderer'); + logMessage('[SMARTX][renderer] Handle SmartX outstream renderer'); var smartPlayObj = { minAdWidth: confMinAdWidth, @@ -392,7 +392,7 @@ function createOutstreamConfig(bid) { // eslint-disable-next-line let _outstreamPlayer = new OutstreamPlayer(divID, smartPlayObj); } catch (e) { - utils.logError('[SMARTX][renderer] Error caught: ' + e); + logError('[SMARTX][renderer] Error caught: ' + e); } return smartPlayObj; } @@ -404,17 +404,17 @@ function createOutstreamConfig(bid) { * @returns {*|number} floor price */ function getBidFloor(bid) { - let floor = utils.getBidIdParameter('bidfloor', bid.params); - let floorcur = utils.getBidIdParameter('bidfloorcur', bid.params) || 'EUR'; + let floor = getBidIdParameter('bidfloor', bid.params); + let floorcur = getBidIdParameter('bidfloorcur', bid.params) || 'EUR'; - if (!floor && utils.isFn(bid.getFloor)) { + if (!floor && isFn(bid.getFloor)) { const floorObj = bid.getFloor({ currency: floorcur, mediaType: '*', size: '*' }); - if (utils.isPlainObject(floorObj) && !isNaN(floorObj.floor) && floorObj.currency === floorcur) { + if (isPlainObject(floorObj) && !isNaN(floorObj.floor) && floorObj.currency === floorcur) { floor = floorObj.floor; } } diff --git a/modules/smartyadsBidAdapter.js b/modules/smartyadsBidAdapter.js index 9c38cb89492..b999d02b059 100644 --- a/modules/smartyadsBidAdapter.js +++ b/modules/smartyadsBidAdapter.js @@ -1,7 +1,7 @@ +import { logMessage } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'smartyads'; const AD_URL = 'https://n1.smartyads.com/?c=o&m=prebid&secret_key=prebid_js'; @@ -40,7 +40,7 @@ export const spec = { winTop = window.top; } catch (e) { location = winTop.location; - utils.logMessage(e); + logMessage(e); }; let placements = []; let request = { diff --git a/modules/smilewantedBidAdapter.js b/modules/smilewantedBidAdapter.js index 65f166566fe..73bd6101670 100644 --- a/modules/smilewantedBidAdapter.js +++ b/modules/smilewantedBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isArray, logError, logWarn, isFn, isPlainObject } from '../src/utils.js'; import { Renderer } from '../src/Renderer.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; @@ -108,13 +108,13 @@ export const spec = { } bidResponse.meta = {}; - if (response.meta && response.meta.advertiserDomains && utils.isArray(response.meta.advertiserDomains)) { + if (response.meta && response.meta.advertiserDomains && isArray(response.meta.advertiserDomains)) { bidResponse.meta.advertiserDomains = response.meta.advertiserDomains; } bidResponses.push(bidResponse); } } catch (error) { - utils.logError('Error while parsing smilewanted response', error); + logError('Error while parsing smilewanted response', error); } return bidResponses; }, @@ -170,7 +170,7 @@ function newRenderer(bidRequest, bidResponse) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on newRenderer', err); + logWarn('Prebid Error calling setRender on newRenderer', err); } return renderer; } @@ -197,13 +197,13 @@ function outstreamRender(bid) { * @returns {*|number} floor price */ function getBidFloor(bid) { - if (utils.isFn(bid.getFloor)) { + if (isFn(bid.getFloor)) { const floorInfo = bid.getFloor({ currency: 'USD', mediaType: 'banner', size: bid.sizes.map(size => ({ w: size[0], h: size[1] })) }); - if (utils.isPlainObject(floorInfo) && !isNaN(floorInfo.floor) && floorInfo.currency === 'USD') { + if (isPlainObject(floorInfo) && !isNaN(floorInfo.floor) && floorInfo.currency === 'USD') { return parseFloat(floorInfo.floor); } } diff --git a/modules/sonobiAnalyticsAdapter.js b/modules/sonobiAnalyticsAdapter.js index d69276e915c..0de6647149a 100644 --- a/modules/sonobiAnalyticsAdapter.js +++ b/modules/sonobiAnalyticsAdapter.js @@ -1,9 +1,9 @@ +import { deepClone, logInfo, logError } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; import {ajaxBuilder} from '../src/ajax.js'; -const utils = require('../src/utils.js'); let ajax = ajaxBuilder(0); const DEFAULT_EVENT_URL = 'apex.go.sonobi.com/keymaker'; @@ -91,7 +91,7 @@ function addToAuctionQueue(auctionId, id) { if (item.bidid !== id) { return true; } return auction.stats[id].data.p !== item.p; }); - auction.queue.push(utils.deepClone(auction.stats[id].data)); + auction.queue.push(deepClone(auction.stats[id].data)); if (!auction.qTimeout) { auction.qTimeout = setTimeout(() => { sendQueue(auctionId); @@ -102,18 +102,18 @@ function updateBidStats(auctionId, id, data) { let auction = auctionCache[auctionId]; auction.stats[id].data = {...auction.stats[id].data, ...data}; addToAuctionQueue(auctionId, id); - logInfo('Updated Bid Stats: ', auction.stats[id]); + _logInfo('Updated Bid Stats: ', auction.stats[id]); return auction.stats[id]; } function handleOtherEvents(eventType, args) { - logInfo('Other Event: ' + eventType, args); + _logInfo('Other Event: ' + eventType, args); } function handlerAuctionInit(args) { auctionCache[args.auctionId] = buildAuctionEntity(args); deleteOldAuctions(); - logInfo('Auction Init', args); + _logInfo('Auction Init', args); } function handlerBidRequested(args) { let auction = auctionCache[args.auctionId]; @@ -127,14 +127,14 @@ function handlerBidRequested(args) { addToAuctionQueue(args.auctionId, built.bidid); }) - logInfo('Bids Requested ', data); + _logInfo('Bids Requested ', data); } function handlerBidAdjustment(args) { - logInfo('Bid Adjustment', args); + _logInfo('Bid Adjustment', args); } function handlerBidderDone(args) { - logInfo('Bidder Done', args); + _logInfo('Bidder Done', args); } function handlerAuctionEnd(args) { @@ -152,24 +152,24 @@ function handlerAuctionEnd(args) { updateBidStats(args.auctionId, bidId, {response: 4}); } }) - logInfo('Auction End', args); - logInfo('Auction Cache', auctionCache[args.auctionId].stats); + _logInfo('Auction End', args); + _logInfo('Auction Cache', auctionCache[args.auctionId].stats); } function handlerBidWon(args) { let {auctionId, requestId} = args; let res = updateBidStats(auctionId, requestId, {p: 3, response: 6}); - logInfo('Bid Won ', args); - logInfo('Bid Update Result: ', res); + _logInfo('Bid Won ', args); + _logInfo('Bid Update Result: ', res); } function handlerBidResponse(args) { let {auctionId, requestId, cpm, size, timeToRespond} = args; updateBidStats(auctionId, requestId, {bid: cpm, s: size, jsLatency: timeToRespond, latency: timeToRespond, p: 2, response: 9}); - logInfo('Bid Response ', args); + _logInfo('Bid Response ', args); } function handlerBidTimeout(args) { let {auctionId, bidId} = args; - logInfo('Bid Timeout ', args); + _logInfo('Bid Timeout ', args); updateBidStats(auctionId, bidId, {p: 2, response: 0, latency: args.timeout, jsLatency: args.timeout}); } let sonobiAdapter = Object.assign(adapter({url: DEFAULT_EVENT_URL, analyticsType}), { @@ -211,7 +211,7 @@ sonobiAdapter.originEnableAnalytics = sonobiAdapter.enableAnalytics; sonobiAdapter.enableAnalytics = function (config) { if (this.initConfig(config)) { - logInfo('Analytics adapter enabled', initOptions); + _logInfo('Analytics adapter enabled', initOptions); sonobiAdapter.originEnableAnalytics(config); } }; @@ -219,17 +219,17 @@ sonobiAdapter.enableAnalytics = function (config) { sonobiAdapter.initConfig = function (config) { let isCorrectConfig = true; initOptions = {}; - initOptions.options = utils.deepClone(config.options); + initOptions.options = deepClone(config.options); initOptions.pubId = initOptions.options.pubId || null; initOptions.siteId = initOptions.options.siteId || null; initOptions.delay = initOptions.options.delay || QUEUE_TIMEOUT_DEFAULT; if (!initOptions.pubId) { - logError('"options.pubId" is empty'); + _logError('"options.pubId" is empty'); isCorrectConfig = false; } if (!initOptions.siteId) { - logError('"options.siteId" is empty'); + _logError('"options.siteId" is empty'); isCorrectConfig = false; } @@ -247,7 +247,7 @@ sonobiAdapter.sendData = function (auction, data) { let url = 'https://' + initOptions.server + '?pageviewid=' + auction.id + '&corscred=1&pubId=' + initOptions.pubId + '&siteId=' + initOptions.siteId; ajax( url, - function () { logInfo('Auction [' + auction.id + '] sent ', data); }, + function () { _logInfo('Auction [' + auction.id + '] sent ', data); }, JSON.stringify(data), { method: 'POST', @@ -257,12 +257,12 @@ sonobiAdapter.sendData = function (auction, data) { ); } -function logInfo(message, meta) { - utils.logInfo(buildLogMessage(message), meta); +function _logInfo(message, meta) { + logInfo(buildLogMessage(message), meta); } -function logError(message) { - utils.logError(buildLogMessage(message)); +function _logError(message) { + logError(buildLogMessage(message)); } function buildLogMessage(message) { diff --git a/modules/sortableAnalyticsAdapter.js b/modules/sortableAnalyticsAdapter.js index 73ce1393c23..76d3ca63d69 100644 --- a/modules/sortableAnalyticsAdapter.js +++ b/modules/sortableAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { logInfo, getParameterByName, getOldestHighestCpmBid } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getGlobal} from '../src/prebidGlobal.js'; import { config } from '../src/config.js'; @@ -160,7 +160,7 @@ function getSessionParams() { sessionParams = paramsFromStorage && stillValid(paramsFromStorage) ? paramsFromStorage : null; } sessionParams = sessionParams || {'created': +new Date(), 'sessionId': generateRandomId()}; - const urlParams = UTM_PARAMS.map(utils.getParameterByName); + const urlParams = UTM_PARAMS.map(getParameterByName); if (UTM_PARAMS.every(key => !sessionParams[key])) { UTM_PARAMS.forEach((v, i) => sessionParams[v] = urlParams[i] || sessionParams[v]); sessionParams.created = +new Date(); @@ -318,7 +318,7 @@ function sendEvents(events) { 'method': 'POST', 'withCredentials': true }; - const onSend = () => utils.logInfo('Sortable Analytics data sent'); + const onSend = () => logInfo('Sortable Analytics data sent'); ajax(url, onSend, JSON.stringify(mergedEvents), options); } @@ -444,7 +444,7 @@ function handleAuctionEnd(event) { const events = Object.keys(adUnits).map(adUnitCode => { const bidderKeys = Object.keys(auction.adUnits[adUnitCode].bids); const bids = bidderKeys.map(bidderCode => auction.adUnits[adUnitCode].bids[bidderCode]); - const highestBid = bids.length ? bids.reduce(utils.getOldestHighestCpmBid) : null; + const highestBid = bids.length ? bids.reduce(getOldestHighestCpmBid) : null; return bidderKeys.map(bidderCode => { const bid = auction.adUnits[adUnitCode].bids[bidderCode]; if (highestBid && highestBid.cpm) { @@ -507,7 +507,7 @@ sortableAnalyticsAdapter.originEnableAnalytics = sortableAnalyticsAdapter.enable sortableAnalyticsAdapter.enableAnalytics = function (setupConfig) { if (this.initConfig(setupConfig)) { - utils.logInfo('Sortable Analytics adapter enabled'); + logInfo('Sortable Analytics adapter enabled'); sortableAnalyticsAdapter.originEnableAnalytics(setupConfig); } }; From c3d518f8eb5b00251493472640b84a2717691cbb Mon Sep 17 00:00:00 2001 From: Marcin Grzebyk <35067477+marcin15g@users.noreply.github.com> Date: Tue, 28 Sep 2021 22:44:39 +0200 Subject: [PATCH 32/84] JustPremium - schain support added (#7506) --- modules/justpremiumBidAdapter.js | 6 +++++- .../spec/modules/justpremiumBidAdapter_spec.js | 18 ++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/modules/justpremiumBidAdapter.js b/modules/justpremiumBidAdapter.js index da30ee16427..fa0f939affc 100644 --- a/modules/justpremiumBidAdapter.js +++ b/modules/justpremiumBidAdapter.js @@ -4,7 +4,7 @@ import { deepAccess } from '../src/utils.js'; const BIDDER_CODE = 'justpremium' const GVLID = 62 const ENDPOINT_URL = 'https://pre.ads.justpremium.com/v/2.0/t/xhr' -const JP_ADAPTER_VERSION = '1.7' +const JP_ADAPTER_VERSION = '1.8' const pixels = [] export const spec = { @@ -65,6 +65,10 @@ export const spec = { jp_adapter: JP_ADAPTER_VERSION } + if (validBidRequests[0].schain) { + payload.schain = validBidRequests[0].schain; + } + const payloadString = JSON.stringify(payload) return { diff --git a/test/spec/modules/justpremiumBidAdapter_spec.js b/test/spec/modules/justpremiumBidAdapter_spec.js index cb3648cba44..74526660f61 100644 --- a/test/spec/modules/justpremiumBidAdapter_spec.js +++ b/test/spec/modules/justpremiumBidAdapter_spec.js @@ -12,6 +12,18 @@ describe('justpremium adapter', function () { sandbox.restore(); }); + let schainConfig = { + 'ver': '1.0', + 'complete': 1, + 'nodes': [ + { + 'asi': 'indirectseller.com', + 'sid': '00001', + 'hp': 1 + } + ] + } + let adUnits = [ { adUnitCode: 'div-gpt-ad-1471513102552-1', @@ -33,7 +45,8 @@ describe('justpremium adapter', function () { params: { zone: 28313, allow: ['lb', 'wp'] - } + }, + schain: schainConfig }, { adUnitCode: 'div-gpt-ad-1471513102552-2', @@ -75,6 +88,7 @@ describe('justpremium adapter', function () { expect(jpxRequest).to.not.equal(null) expect(jpxRequest.zone).to.not.equal('undefined') expect(bidderRequest.refererInfo.referer).to.equal('https://justpremium.com') + expect(jpxRequest.schain).to.deep.equal(schainConfig) expect(jpxRequest.sw).to.equal(window.top.screen.width) expect(jpxRequest.sh).to.equal(window.top.screen.height) expect(jpxRequest.ww).to.equal(window.top.innerWidth) @@ -83,7 +97,7 @@ describe('justpremium adapter', function () { expect(jpxRequest.id).to.equal(adUnits[0].params.zone) expect(jpxRequest.mediaTypes && jpxRequest.mediaTypes.banner && jpxRequest.mediaTypes.banner.sizes).to.not.equal('undefined') expect(jpxRequest.version.prebid).to.equal('$prebid.version$') - expect(jpxRequest.version.jp_adapter).to.equal('1.7') + expect(jpxRequest.version.jp_adapter).to.equal('1.8') expect(jpxRequest.pubcid).to.equal('0000000') expect(jpxRequest.uids.tdid).to.equal('1111111') expect(jpxRequest.uids.id5id.uid).to.equal('2222222') From 0d56358e107c8a14ef802fea271b75c34e4ff412 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 15:11:04 -0700 Subject: [PATCH 33/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7491) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/mediakeysBidAdapter.js | 80 +++++++++++----------- modules/medianetAnalyticsAdapter.js | 68 +++++++++---------- modules/medianetBidAdapter.js | 66 +++++++++--------- modules/medianetRtdProvider.js | 14 ++-- modules/merkleIdSystem.js | 38 +++++------ modules/mgidBidAdapter.js | 100 ++++++++++++++-------------- modules/microadBidAdapter.js | 6 +- modules/mwOpenLinkIdSystem.js | 14 ++-- modules/nativoBidAdapter.js | 6 +- modules/naveggIdSystem.js | 6 +- modules/nextMillenniumBidAdapter.js | 12 ++-- modules/nobidBidAdapter.js | 20 +++--- modules/novatiqIdSystem.js | 16 ++--- modules/oneVideoBidAdapter.js | 40 +++++------ modules/onomagicBidAdapter.js | 32 ++++----- 15 files changed, 259 insertions(+), 259 deletions(-) diff --git a/modules/mediakeysBidAdapter.js b/modules/mediakeysBidAdapter.js index 539d2f6c9cf..5b48e732942 100644 --- a/modules/mediakeysBidAdapter.js +++ b/modules/mediakeysBidAdapter.js @@ -1,7 +1,7 @@ +import { getWindowTop, isFn, logWarn, getDNT, deepAccess, isArray, inIframe, mergeDeep, isStr, isEmpty, deepSetValue, deepClone, parseUrl, cleanObj, logError, triggerPixel } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import { createEidsArray } from './userId/eids.js'; const AUCTION_TYPE = 1; @@ -19,7 +19,7 @@ const NET_REVENUE = true; */ function canAccessTopWindow() { try { - return !!utils.getWindowTop().location.href; + return !!getWindowTop().location.href; } catch (error) { return false; } @@ -65,12 +65,12 @@ function getOS() { * @returns {number|boolean} */ function getFloor(bid, mediaType, size = '*') { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return false; } if (SUPPORTED_MEDIA_TYPES.indexOf(mediaType) === -1) { - utils.logWarn(`${BIDDER_CODE}: Unable to detect floor price for unsupported mediaType ${mediaType}. No floor will be used.`); + logWarn(`${BIDDER_CODE}: Unable to detect floor price for unsupported mediaType ${mediaType}. No floor will be used.`); return false; } @@ -99,7 +99,7 @@ function createOrtbTemplate() { device: { ip: '', js: 1, - dnt: utils.getDNT(), + dnt: getDNT(), ua: navigator.userAgent, devicetype: getDeviceType(), os: getOS(), @@ -128,10 +128,10 @@ function createOrtbTemplate() { */ function createBannerImp(bid) { let sizes = bid.mediaTypes.banner.sizes; - const params = utils.deepAccess(bid, 'params', {}); + const params = deepAccess(bid, 'params', {}); - if (!utils.isArray(sizes) || !sizes.length) { - utils.logWarn(`${BIDDER_CODE}: mediaTypes.banner.size missing for adunit: ${bid.params.adUnit}. Ignoring the banner impression in the adunit.`); + if (!isArray(sizes) || !sizes.length) { + logWarn(`${BIDDER_CODE}: mediaTypes.banner.size missing for adunit: ${bid.params.adUnit}. Ignoring the banner impression in the adunit.`); } else { const banner = {}; @@ -146,7 +146,7 @@ function createBannerImp(bid) { }); banner.format = format; - banner.topframe = utils.inIframe() ? 0 : 1; + banner.topframe = inIframe() ? 0 : 1; banner.pos = params.pos || 0; return banner; @@ -185,10 +185,10 @@ function createImp(bid) { } // handle FPD for imp. - const ortb2Imp = utils.deepAccess(bid, 'ortb2Imp.ext.data'); + const ortb2Imp = deepAccess(bid, 'ortb2Imp.ext.data'); if (ortb2Imp) { const fpd = { ...bid.ortb2Imp }; - utils.mergeDeep(imp, fpd); + mergeDeep(imp, fpd); } return imp; @@ -202,13 +202,13 @@ function createImp(bid) { * @returns {string|null} */ function getPrimaryCatFromResponse(cat) { - if (!cat || (utils.isArray(cat) && !cat.length)) { + if (!cat || (isArray(cat) && !cat.length)) { return; } - if (utils.isArray(cat)) { + if (isArray(cat)) { return cat[0]; - } else if (utils.isStr(cat)) { + } else if (isStr(cat)) { return cat; } } @@ -221,7 +221,7 @@ export const spec = { supportedMediaTypes: SUPPORTED_MEDIA_TYPES, isBidRequestValid: function(bid) { - return !!(bid && !utils.isEmpty(bid)); + return !!(bid && !isEmpty(bid)); }, buildRequests: function(validBidRequests, bidderRequest) { @@ -229,11 +229,11 @@ export const spec = { // Pass the auctionId as ortb2 id // See https://github.com/prebid/Prebid.js/issues/6563 - utils.deepSetValue(payload, 'id', bidderRequest.auctionId); - utils.deepSetValue(payload, 'source.tid', bidderRequest.auctionId); + deepSetValue(payload, 'id', bidderRequest.auctionId); + deepSetValue(payload, 'source.tid', bidderRequest.auctionId); validBidRequests.forEach(validBid => { - let bid = utils.deepClone(validBid); + let bid = deepClone(validBid); // No additional params atm. const imp = createImp(bid); @@ -242,37 +242,37 @@ export const spec = { }); if (validBidRequests[0].schain) { - utils.deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); + deepSetValue(payload, 'source.ext.schain', validBidRequests[0].schain); } if (bidderRequest && bidderRequest.gdprConsent) { - utils.deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); - utils.deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); + deepSetValue(payload, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(payload, 'regs.ext.gdpr', (bidderRequest.gdprConsent.gdprApplies ? 1 : 0)); } if (bidderRequest && bidderRequest.uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (config.getConfig('coppa') === true) { - utils.deepSetValue(payload, 'regs.coppa', 1); + deepSetValue(payload, 'regs.coppa', 1); } - if (utils.deepAccess(validBidRequests[0], 'userId')) { - utils.deepSetValue(payload, 'user.ext.eids', createEidsArray(validBidRequests[0].userId)); + if (deepAccess(validBidRequests[0], 'userId')) { + deepSetValue(payload, 'user.ext.eids', createEidsArray(validBidRequests[0].userId)); } // Assign payload.site from refererinfo if (bidderRequest.refererInfo) { if (bidderRequest.refererInfo.reachedTop) { const sitePage = bidderRequest.refererInfo.referer; - utils.deepSetValue(payload, 'site.page', sitePage); - utils.deepSetValue(payload, 'site.domain', utils.parseUrl(sitePage, { + deepSetValue(payload, 'site.page', sitePage); + deepSetValue(payload, 'site.domain', parseUrl(sitePage, { noDecodeWholeURL: true }).hostname); if (canAccessTopWindow()) { - utils.deepSetValue(payload, 'site.ref', utils.getWindowTop().document.referrer); + deepSetValue(payload, 'site.ref', getWindowTop().document.referrer); } } } @@ -280,15 +280,15 @@ export const spec = { // Handle First Party Data (need publisher fpd setup) const fpd = config.getConfig('ortb2') || {}; if (fpd.site) { - utils.mergeDeep(payload, { site: fpd.site }); + mergeDeep(payload, { site: fpd.site }); } if (fpd.user) { - utils.mergeDeep(payload, { user: fpd.user }); + mergeDeep(payload, { user: fpd.user }); } // Here we can handle device.geo prop - const deviceGeo = utils.deepAccess(fpd, 'device.geo'); + const deviceGeo = deepAccess(fpd, 'device.geo'); if (deviceGeo) { - utils.mergeDeep(payload.device, { geo: deviceGeo }); + mergeDeep(payload.device, { geo: deviceGeo }); } const request = { @@ -307,19 +307,19 @@ export const spec = { const bidResponses = []; try { - if (serverResponse.body && serverResponse.body.seatbid && utils.isArray(serverResponse.body.seatbid)) { + if (serverResponse.body && serverResponse.body.seatbid && isArray(serverResponse.body.seatbid)) { const currency = serverResponse.body.cur || DEFAULT_CURRENCY; const referrer = bidRequest.site && bidRequest.site.ref ? bidRequest.site.ref : ''; serverResponse.body.seatbid.forEach(bidderSeat => { - if (!utils.isArray(bidderSeat.bid) || !bidderSeat.bid.length) { + if (!isArray(bidderSeat.bid) || !bidderSeat.bid.length) { return; } bidderSeat.bid.forEach(bid => { let mediaType; // Actually only BANNER is supported, but other types will be added soon. - switch (utils.deepAccess(bid, 'ext.prebid.type')) { + switch (deepAccess(bid, 'ext.prebid.type')) { case 'V': mediaType = VIDEO; break; @@ -332,8 +332,8 @@ export const spec = { const meta = { advertiserDomains: (Array.isArray(bid.adomain) && bid.adomain.length) ? bid.adomain : [], - advertiserName: utils.deepAccess(bid, 'ext.advertiser_name', null), - agencyName: utils.deepAccess(bid, 'ext.agency_name', null), + advertiserName: deepAccess(bid, 'ext.advertiser_name', null), + agencyName: deepAccess(bid, 'ext.agency_name', null), primaryCatId: getPrimaryCatFromResponse(bid.cat), mediaType } @@ -352,7 +352,7 @@ export const spec = { ad: bid.adm, mediaType, burl: bid.burl, - meta: utils.cleanObj(meta) + meta: cleanObj(meta) }; bidResponses.push(newBid); @@ -360,7 +360,7 @@ export const spec = { }); } } catch (e) { - utils.logError(BIDDER_CODE, e); + logError(BIDDER_CODE, e); } return bidResponses; @@ -373,7 +373,7 @@ export const spec = { const url = bid.burl.replace(/\$\{AUCTION_PRICE\}/, bid.cpm); - utils.triggerPixel(url); + triggerPixel(url); } } diff --git a/modules/medianetAnalyticsAdapter.js b/modules/medianetAnalyticsAdapter.js index 45fb39d8c82..e281dde8ad0 100644 --- a/modules/medianetAnalyticsAdapter.js +++ b/modules/medianetAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { triggerPixel, deepAccess, getWindowTop, uniques, groupBy, isEmpty, _map, isPlainObject, logInfo, logError } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; -import * as utils from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { getRefererInfo } from '../src/refererDetection.js'; import { AUCTION_COMPLETED, AUCTION_IN_PROGRESS, getPriceGranularity } from '../src/auction.js'; @@ -66,7 +66,7 @@ class ErrorLogger { send() { let url = EVENT_PIXEL_URL + '?' + formatQS(this); - utils.triggerPixel(url); + triggerPixel(url); } } @@ -126,7 +126,7 @@ class Configure { } overrideDomainLevelData(response) { - const domain = utils.deepAccess(response, 'domain.' + pageDetails.domain); + const domain = deepAccess(response, 'domain.' + pageDetails.domain); if (domain) { this.setDataFromResponse(domain); } @@ -149,14 +149,14 @@ class Configure { init() { // Forces Logging % to 100% let urlObj = URL.parseUrl(pageDetails.page); - if (utils.deepAccess(urlObj, 'search.medianet_test') || urlObj.hostname === 'localhost') { + if (deepAccess(urlObj, 'search.medianet_test') || urlObj.hostname === 'localhost') { this.loggingPercent = 100; this.ajaxState = CONFIG_PASS; this.debug = true; return; } - if (utils.deepAccess(urlObj, 'search.mnet_setconfig')) { - this.mnetDebugConfig = utils.deepAccess(urlObj, 'search.mnet_setconfig'); + if (deepAccess(urlObj, 'search.mnet_setconfig')) { + this.mnetDebugConfig = deepAccess(urlObj, 'search.mnet_setconfig'); } ajax( this._configURL(), @@ -201,7 +201,7 @@ class PageDetail { _getAttributeFromSelector(selector, attribute) { try { - let doc = utils.getWindowTop().document; + let doc = getWindowTop().document; let element = doc.querySelector(selector); if (element !== null && element[attribute]) { return element[attribute]; @@ -210,7 +210,7 @@ class PageDetail { } _getAbsoluteUrl(url) { - let aTag = utils.getWindowTop().document.createElement('a'); + let aTag = getWindowTop().document.createElement('a'); aTag.href = url; return aTag.href; @@ -358,8 +358,8 @@ class Auction { flrdata: this._mergeFieldsToLog({ ln: this.floorData.location, skp: this.floorData.skipped, - enfj: utils.deepAccess(this.floorData, 'enforcements.enforceJS'), - enfd: utils.deepAccess(this.floorData, 'enforcements.floorDeals'), + enfj: deepAccess(this.floorData, 'enforcements.enforceJS'), + enfd: deepAccess(this.floorData, 'enforcements.floorDeals'), sr: this.floorData.skipRate, fs: this.floorData.fetchStatus }), @@ -411,7 +411,7 @@ function auctionInitHandler({auctionId, adUnits, timeout, timestamp, bidderReque auctions[auctionId].auctionInitTime = timestamp; } addAddSlots(auctionId, adUnits, timeout); - const floorData = utils.deepAccess(bidderRequests, '0.bids.0.floorData'); + const floorData = deepAccess(bidderRequests, '0.bids.0.floorData'); if (floorData) { auctions[auctionId].floorData = {...floorData}; } @@ -419,10 +419,10 @@ function auctionInitHandler({auctionId, adUnits, timeout, timestamp, bidderReque function addAddSlots(auctionId, adUnits, tmax) { adUnits = adUnits || []; - const groupedAdUnits = utils.groupBy(adUnits, 'code'); + const groupedAdUnits = groupBy(adUnits, 'code'); Object.keys(groupedAdUnits).forEach((adUnitCode) => { const adUnits = groupedAdUnits[adUnitCode]; - const supplyAdCode = utils.deepAccess(adUnits, '0.adUnitCode') || adUnitCode; + const supplyAdCode = deepAccess(adUnits, '0.adUnitCode') || adUnitCode; let context = ''; let adext = {}; @@ -430,17 +430,17 @@ function addAddSlots(auctionId, adUnits, tmax) { const oSizes = {banner: [], video: []}; adUnits.forEach(({mediaTypes, sizes, ext}) => { mediaTypes = mediaTypes || {}; - adext = Object.assign(adext, ext || utils.deepAccess(mediaTypes, 'banner.ext')); - context = utils.deepAccess(mediaTypes, 'video.context') || context; + adext = Object.assign(adext, ext || deepAccess(mediaTypes, 'banner.ext')); + context = deepAccess(mediaTypes, 'video.context') || context; Object.keys(mediaTypes).forEach((mediaType) => mediaTypeMap[mediaType] = 1); const sizeObject = _getSizes(mediaTypes, sizes); sizeObject.banner.forEach(size => oSizes.banner.push(size)); sizeObject.video.forEach(size => oSizes.video.push(size)); }); - adext = utils.isEmpty(adext) ? undefined : adext; - oSizes.banner = oSizes.banner.filter(utils.uniques); - oSizes.video = oSizes.video.filter(utils.uniques); + adext = isEmpty(adext) ? undefined : adext; + oSizes.banner = oSizes.banner.filter(uniques); + oSizes.video = oSizes.video.filter(uniques); oSizes.native = mediaTypeMap.native === 1 ? [[1, 1].join('x')] : []; const allMediaTypeSizes = [].concat(oSizes.banner, oSizes.native, oSizes.video); const mediaTypes = Object.keys(mediaTypeMap).join('|'); @@ -468,17 +468,17 @@ function bidRequestedHandler({ auctionId, auctionStart, bids, start, uspConsent, const bidObj = new Bid(bidId, bidder, src, start, adUnitCode, mediaTypes && Object.keys(mediaTypes).join('|'), requestSizes); auctions[auctionId].addBid(bidObj); if (bidder === MEDIANET_BIDDER_CODE) { - bidObj.crid = utils.deepAccess(bid, 'params.crid'); - bidObj.pubcrid = utils.deepAccess(bid, 'params.crid'); + bidObj.crid = deepAccess(bid, 'params.crid'); + bidObj.pubcrid = deepAccess(bid, 'params.crid'); auctions[auctionId].adSlots[adUnitCode].medianetPresent = 1; } }); } function _getSizes(mediaTypes, sizes) { - const banner = utils.deepAccess(mediaTypes, 'banner.sizes') || sizes || []; - const native = utils.deepAccess(mediaTypes, 'native') ? [[1, 1]] : []; - const playerSize = utils.deepAccess(mediaTypes, 'video.playerSize') || []; + const banner = deepAccess(mediaTypes, 'banner.sizes') || sizes || []; + const native = deepAccess(mediaTypes, 'native') ? [[1, 1]] : []; + const playerSize = deepAccess(mediaTypes, 'video.playerSize') || []; let video = []; if (playerSize.length === 2) { video = [playerSize] @@ -506,10 +506,10 @@ function bidResponseHandler(bid) { { cpm, width, height, mediaType, timeToRespond, dealId, creativeId }, { adId, currency } ); - bidObj.floorPrice = utils.deepAccess(bid, 'floorData.floorValue'); - bidObj.floorRule = utils.deepAccess(bid, 'floorData.floorRule'); + bidObj.floorPrice = deepAccess(bid, 'floorData.floorValue'); + bidObj.floorRule = deepAccess(bid, 'floorData.floorRule'); bidObj.originalCpm = originalCpm || cpm; - let dfpbd = utils.deepAccess(bid, 'adserverTargeting.hb_pb'); + let dfpbd = deepAccess(bid, 'adserverTargeting.hb_pb'); if (!dfpbd) { let priceGranularity = getPriceGranularity(mediaType, bid); let priceGranularityKey = PRICE_GRANULARITY[priceGranularity]; @@ -598,8 +598,8 @@ function setTargetingHandler(params) { auctionObj.bids.forEach(bid => { if (bid.bidder === DUMMY_BIDDER && bid.adUnitCode === adunit) { bid.iwb = bidAdIds.length === 0 ? 0 : 1; - bid.width = utils.deepAccess(winningBid, 'width'); - bid.height = utils.deepAccess(winningBid, 'height'); + bid.width = deepAccess(winningBid, 'width'); + bid.height = deepAccess(winningBid, 'height'); } }); sendEvent(auctionId, adunit, LOG_TYPE.APPR); @@ -658,7 +658,7 @@ function getCommonLoggingData(acid, adtag) { function fireAuctionLog(acid, adtag, logType) { let commonParams = getCommonLoggingData(acid, adtag); commonParams.lgtp = logType; - let targeting = utils.deepAccess(commonParams, 'targ'); + let targeting = deepAccess(commonParams, 'targ'); Object.keys(commonParams).forEach((key) => (commonParams[key] == null) && delete commonParams[key]); delete commonParams.targ; @@ -686,11 +686,11 @@ function fireAuctionLog(acid, adtag, logType) { } function formatQS(data) { - return utils._map(data, (value, key) => { + return _map(data, (value, key) => { if (value === undefined) { return key + '='; } - if (utils.isPlainObject(value)) { + if (isPlainObject(value)) { value = JSON.stringify(value); } return key + '=' + encodeURIComponent(value); @@ -699,7 +699,7 @@ function formatQS(data) { function firePixel(qs) { logsQueue.push(ENDPOINT + '&' + qs); - utils.triggerPixel(ENDPOINT + '&' + qs); + triggerPixel(ENDPOINT + '&' + qs); } class URL { @@ -740,7 +740,7 @@ let medianetAnalytics = Object.assign(adapter({URL, analyticsType}), { }, track({ eventType, args }) { if (config.debug) { - utils.logInfo(eventType, args); + logInfo(eventType, args); } switch (eventType) { case CONSTANTS.EVENTS.AUCTION_INIT: { @@ -782,7 +782,7 @@ medianetAnalytics.originEnableAnalytics = medianetAnalytics.enableAnalytics; medianetAnalytics.enableAnalytics = function (configuration) { if (!configuration || !configuration.options || !configuration.options.cid) { - utils.logError('Media.net Analytics adapter: cid is required.'); + logError('Media.net Analytics adapter: cid is required.'); return; } $$PREBID_GLOBAL$$.medianetGlobals = $$PREBID_GLOBAL$$.medianetGlobals || {}; diff --git a/modules/medianetBidAdapter.js b/modules/medianetBidAdapter.js index d78f4a70e2c..db3921c9a47 100644 --- a/modules/medianetBidAdapter.js +++ b/modules/medianetBidAdapter.js @@ -1,5 +1,5 @@ +import { parseUrl, getWindowTop, isArray, getGptSlotInfoForAdUnitCode, isStr, deepAccess, isEmpty, logError, triggerPixel, buildUrl, isEmptyStr, logInfo } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import { getRefererInfo } from '../src/refererDetection.js'; @@ -27,7 +27,7 @@ window.mnet = window.mnet || {}; window.mnet.queue = window.mnet.queue || []; mnData.urlData = { - domain: utils.parseUrl(refererInfo.referer).hostname, + domain: parseUrl(refererInfo.referer).hostname, page: refererInfo.referer, isTop: refererInfo.reachedTop } @@ -78,7 +78,7 @@ function getUrlFromSelector(selector, attribute) { function getAttributeFromSelector(selector, attribute) { try { - let doc = utils.getWindowTop().document; + let doc = getWindowTop().document; let element = doc.querySelector(selector); if (element !== null && element[attribute]) { return element[attribute]; @@ -87,7 +87,7 @@ function getAttributeFromSelector(selector, attribute) { } function getAbsoluteUrl(url) { - let aTag = utils.getWindowTop().document.createElement('a'); + let aTag = getWindowTop().document.createElement('a'); aTag.href = url; return aTag.href; @@ -98,7 +98,7 @@ function filterUrlsByType(urls, type) { } function transformSizes(sizes) { - if (utils.isArray(sizes) && sizes.length === 2 && !utils.isArray(sizes[0])) { + if (isArray(sizes) && sizes.length === 2 && !isArray(sizes[0])) { return [getSize(sizes)]; } @@ -123,8 +123,8 @@ function getCoordinates(adUnitCode) { let element = document.getElementById(adUnitCode); if (!element && adUnitCode.indexOf('/') !== -1) { // now it means that adUnitCode is GAM AdUnitPath - const {divId} = utils.getGptSlotInfoForAdUnitCode(adUnitCode); - if (utils.isStr(divId)) { + const {divId} = getGptSlotInfoForAdUnitCode(adUnitCode); + if (isStr(divId)) { element = document.getElementById(divId); } } @@ -145,11 +145,11 @@ function getCoordinates(adUnitCode) { } function extParams(bidRequest, bidderRequests) { - const params = utils.deepAccess(bidRequest, 'params'); - const gdpr = utils.deepAccess(bidderRequests, 'gdprConsent'); - const uspConsent = utils.deepAccess(bidderRequests, 'uspConsent'); - const userId = utils.deepAccess(bidRequest, 'userId'); - const sChain = utils.deepAccess(bidRequest, 'schain') || {}; + const params = deepAccess(bidRequest, 'params'); + const gdpr = deepAccess(bidderRequests, 'gdprConsent'); + const uspConsent = deepAccess(bidderRequests, 'uspConsent'); + const userId = deepAccess(bidRequest, 'userId'); + const sChain = deepAccess(bidRequest, 'schain') || {}; const windowSize = spec.getWindowSize(); const gdprApplies = !!(gdpr && gdpr.gdprApplies); const uspApplies = !!(uspConsent); @@ -165,7 +165,7 @@ function extParams(bidRequest, bidderRequests) { windowSize.w !== -1 && windowSize.h !== -1 && { screen: windowSize }, userId && { user_id: userId }, $$PREBID_GLOBAL$$.medianetGlobals.analyticsEnabled && { analytics: true }, - !utils.isEmpty(sChain) && {schain: sChain} + !isEmpty(sChain) && {schain: sChain} ); } @@ -184,13 +184,13 @@ function slotParams(bidRequest) { params.ortb2Imp = bidRequest.ortb2Imp; } - let bannerSizes = utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes') || []; + let bannerSizes = deepAccess(bidRequest, 'mediaTypes.banner.sizes') || []; - const videoInMediaType = utils.deepAccess(bidRequest, 'mediaTypes.video') || {}; - const videoInParams = utils.deepAccess(bidRequest, 'params.video') || {}; + const videoInMediaType = deepAccess(bidRequest, 'mediaTypes.video') || {}; + const videoInParams = deepAccess(bidRequest, 'params.video') || {}; const videoCombinedObj = Object.assign({}, videoInParams, videoInMediaType); - if (!utils.isEmpty(videoCombinedObj)) { + if (!isEmpty(videoCombinedObj)) { params.video = videoCombinedObj; } @@ -201,7 +201,7 @@ function slotParams(bidRequest) { try { params.native = JSON.stringify(bidRequest.nativeParams); } catch (e) { - utils.logError((`${BIDDER_CODE} : Incorrect JSON : bidRequest.nativeParams`)); + logError((`${BIDDER_CODE} : Incorrect JSON : bidRequest.nativeParams`)); } } @@ -319,8 +319,8 @@ function isValidBid(bid) { } function fetchCookieSyncUrls(response) { - if (!utils.isEmpty(response) && response[0].body && - response[0].body.ext && utils.isArray(response[0].body.ext.csUrl)) { + if (!isEmpty(response) && response[0].body && + response[0].body.ext && isArray(response[0].body.ext.csUrl)) { return response[0].body.ext.csUrl; } @@ -328,15 +328,15 @@ function fetchCookieSyncUrls(response) { } function getLoggingData(event, data) { - data = (utils.isArray(data) && data) || []; + data = (isArray(data) && data) || []; let params = {}; params.logid = 'kfk'; params.evtid = 'projectevents'; params.project = 'prebid'; - params.acid = utils.deepAccess(data, '0.auctionId') || ''; + params.acid = deepAccess(data, '0.auctionId') || ''; params.cid = $$PREBID_GLOBAL$$.medianetGlobals.cid || ''; - params.crid = data.map((adunit) => utils.deepAccess(adunit, 'params.0.crid') || adunit.adUnitCode).join('|'); + params.crid = data.map((adunit) => deepAccess(adunit, 'params.0.crid') || adunit.adUnitCode).join('|'); params.adunit_count = data.length || 0; params.dn = mnData.urlData.domain || ''; params.requrl = mnData.urlData.page || ''; @@ -354,7 +354,7 @@ function logEvent (event, data) { hostname: EVENT_PIXEL_URL, search: getLoggingData(event, data) }; - utils.triggerPixel(utils.buildUrl(getParams)); + triggerPixel(buildUrl(getParams)); } function clearMnData() { @@ -362,8 +362,8 @@ function clearMnData() { } function addRenderer(bid) { - const videoContext = utils.deepAccess(bid, 'context') || ''; - const vastTimeout = utils.deepAccess(bid, 'vto'); + const videoContext = deepAccess(bid, 'context') || ''; + const vastTimeout = deepAccess(bid, 'vto'); /* Adding renderer only when the context is Outstream and the provider has responded with a renderer. */ @@ -389,7 +389,7 @@ function newVideoRenderer(bid) { mute: bid.mt } const adUnitCode = bid.dfp_id; - const divId = utils.getGptSlotInfoForAdUnitCode(adUnitCode).divId || adUnitCode; + const divId = getGptSlotInfoForAdUnitCode(adUnitCode).divId || adUnitCode; window.mnet.mediaNetoutstreamPlayer(bid, divId, obj); }); }); @@ -410,12 +410,12 @@ export const spec = { */ isBidRequestValid: function(bid) { if (!bid.params) { - utils.logError(`${BIDDER_CODE} : Missing bid parameters`); + logError(`${BIDDER_CODE} : Missing bid parameters`); return false; } - if (!bid.params.cid || !utils.isStr(bid.params.cid) || utils.isEmptyStr(bid.params.cid)) { - utils.logError(`${BIDDER_CODE} : cid should be a string`); + if (!bid.params.cid || !isStr(bid.params.cid) || isEmptyStr(bid.params.cid)) { + logError(`${BIDDER_CODE} : cid should be a string`); return false; } @@ -450,13 +450,13 @@ export const spec = { let validBids = []; if (!serverResponse || !serverResponse.body) { - utils.logInfo(`${BIDDER_CODE} : response is empty`); + logInfo(`${BIDDER_CODE} : response is empty`); return validBids; } let bids = serverResponse.body.bidList; - if (!utils.isArray(bids) || bids.length === 0) { - utils.logInfo(`${BIDDER_CODE} : no bids`); + if (!isArray(bids) || bids.length === 0) { + logInfo(`${BIDDER_CODE} : no bids`); return validBids; } validBids = bids.filter(bid => isValidBid(bid)); diff --git a/modules/medianetRtdProvider.js b/modules/medianetRtdProvider.js index 77889db5ff2..cd86bf891f3 100644 --- a/modules/medianetRtdProvider.js +++ b/modules/medianetRtdProvider.js @@ -1,5 +1,5 @@ +import { isStr, isEmptyStr, logError, mergeDeep, isFn, insertElement } from '../src/utils.js'; import { submodule } from '../src/hook.js'; -import * as utils from '../src/utils.js'; import { getGlobal } from '../src/prebidGlobal.js'; import includes from 'core-js-pure/features/array/includes.js'; @@ -15,8 +15,8 @@ window.mnjs.que = window.mnjs.que || []; function init(config) { const customerId = config.params && config.params.cid; - if (!customerId || !utils.isStr(customerId) || utils.isEmptyStr(customerId)) { - utils.logError(`${SOURCE}: cid should be a string`); + if (!customerId || !isStr(customerId) || isEmptyStr(customerId)) { + logError(`${SOURCE}: cid should be a string`); return false; } @@ -40,8 +40,8 @@ function getBidRequestData(requestBidsProps, callback, config, userConsent) { const success = (adUnitProps, openRtbProps) => { adUnits.forEach(adUnit => { adUnit[OPEN_RTB_FIELD] = adUnit[OPEN_RTB_FIELD] || {}; - utils.mergeDeep(adUnit[OPEN_RTB_FIELD], openRtbProps[adUnit.code]); - utils.mergeDeep(adUnit, adUnitProps[adUnit.code]); + mergeDeep(adUnit[OPEN_RTB_FIELD], openRtbProps[adUnit.code]); + mergeDeep(adUnit, adUnitProps[adUnit.code]); }); callback(); }; @@ -61,7 +61,7 @@ function onAuctionInitEvent(auctionInit) { function getTargetingData(adUnitCode) { const adUnits = getAdUnits(undefined, adUnitCode); let targetingData = {}; - if (window.mnjs.loaded && utils.isFn(window.mnjs.getTargetingData)) { + if (window.mnjs.loaded && isFn(window.mnjs.getTargetingData)) { targetingData = window.mnjs.getTargetingData(adUnitCode, adUnits, SOURCE) || {}; } const targeting = {}; @@ -86,7 +86,7 @@ function loadRtdScript(customerId) { script.type = 'text/javascript'; script.async = true; script.src = getClientUrl(customerId, window.location.hostname); - utils.insertElement(script, window.document, 'head'); + insertElement(script, window.document, 'head'); } function getAdUnits(adUnits, adUnitCodes) { diff --git a/modules/merkleIdSystem.js b/modules/merkleIdSystem.js index bcb2b943834..5339b653596 100644 --- a/modules/merkleIdSystem.js +++ b/modules/merkleIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logInfo, logError, logWarn } from '../src/utils.js'; import * as ajaxLib from '../src/ajax.js'; import {submodule} from '../src/hook.js' import {getStorageManager} from '../src/storageManager.js'; @@ -34,7 +34,7 @@ function setCookie(name, value, expires) { } function setSession(storage, response) { - utils.logInfo('Merkle setting session '); + logInfo('Merkle setting session '); if (response && response.c && response.c.value && typeof response.c.value === 'string') { setCookie(SESSION_COOKIE_NAME, response.c.value, storage.expires); } @@ -46,7 +46,7 @@ function constructUrl(configParams) { if (session) { url = `${url}&sv_session=${session}`; } - utils.logInfo('Merkle url :' + url); + logInfo('Merkle url :' + url); return url; } @@ -62,19 +62,19 @@ function generateId(configParams, configStorage) { try { responseObj = JSON.parse(response); setSession(configStorage, responseObj) - utils.logInfo('Merkle responseObj ' + JSON.stringify(responseObj)); + logInfo('Merkle responseObj ' + JSON.stringify(responseObj)); } catch (error) { - utils.logError(error); + logError(error); } } const date = new Date().toUTCString(); responseObj.date = date; - utils.logInfo('Merkle responseObj with date ' + JSON.stringify(responseObj)); + logInfo('Merkle responseObj with date ' + JSON.stringify(responseObj)); callback(responseObj); }, error => { - utils.logError(`${MODULE_NAME}: merkleId fetch encountered an error`, error); + logError(`${MODULE_NAME}: merkleId fetch encountered an error`, error); callback(); }, {method: 'GET', withCredentials: true} @@ -98,7 +98,7 @@ export const merkleIdSubmodule = { */ decode(value) { const id = (value && value.pam_id && typeof value.pam_id.id === 'string') ? value.pam_id : undefined; - utils.logInfo('Merkle id ' + JSON.stringify(id)); + logInfo('Merkle id ' + JSON.stringify(id)); return id ? {'merkleId': id} : undefined; }, /** @@ -109,31 +109,31 @@ export const merkleIdSubmodule = { * @returns {IdResponse|undefined} */ getId(config, consentData) { - utils.logInfo('User ID - merkleId generating id'); + logInfo('User ID - merkleId generating id'); const configParams = (config && config.params) || {}; if (!configParams || typeof configParams.vendor !== 'string') { - utils.logError('User ID - merkleId submodule requires a valid vendor to be defined'); + logError('User ID - merkleId submodule requires a valid vendor to be defined'); return; } if (typeof configParams.sv_cid !== 'string') { - utils.logError('User ID - merkleId submodule requires a valid sv_cid string to be defined'); + logError('User ID - merkleId submodule requires a valid sv_cid string to be defined'); return; } if (typeof configParams.sv_pubid !== 'string') { - utils.logError('User ID - merkleId submodule requires a valid sv_pubid string to be defined'); + logError('User ID - merkleId submodule requires a valid sv_pubid string to be defined'); return; } if (consentData && typeof consentData.gdprApplies === 'boolean' && consentData.gdprApplies) { - utils.logError('User ID - merkleId submodule does not currently handle consent strings'); + logError('User ID - merkleId submodule does not currently handle consent strings'); return; } if (typeof configParams.endpoint !== 'string') { - utils.logWarn('User ID - merkleId submodule endpoint string is not defined'); + logWarn('User ID - merkleId submodule endpoint string is not defined'); configParams.endpoint = ID_URL } @@ -146,11 +146,11 @@ export const merkleIdSubmodule = { return {callback: resp}; }, extendId: function (config = {}, consentData, storedId) { - utils.logInfo('User ID - merkleId stored id ' + storedId); + logInfo('User ID - merkleId stored id ' + storedId); const configParams = (config && config.params) || {}; if (consentData && typeof consentData.gdprApplies === 'boolean' && consentData.gdprApplies) { - utils.logError('User ID - merkleId submodule does not currently handle consent strings'); + logError('User ID - merkleId submodule does not currently handle consent strings'); return; } @@ -164,19 +164,19 @@ export const merkleIdSubmodule = { let refreshInSeconds = DEFAULT_REFRESH; if (configParams && configParams.refreshInSeconds && typeof configParams.refreshInSeconds === 'number') { refreshInSeconds = configParams.refreshInSeconds; - utils.logInfo('User ID - merkleId param refreshInSeconds' + refreshInSeconds); + logInfo('User ID - merkleId param refreshInSeconds' + refreshInSeconds); } const storedDate = new Date(storedId.date); let refreshNeeded = false; if (storedDate) { refreshNeeded = storedDate && (Date.now() - storedDate.getTime() > refreshInSeconds * 1000); if (refreshNeeded) { - utils.logInfo('User ID - merkleId needs refreshing id'); + logInfo('User ID - merkleId needs refreshing id'); const resp = generateId(configParams, configStorage) return {callback: resp}; } } - utils.logInfo('User ID - merkleId not refreshed'); + logInfo('User ID - merkleId not refreshed'); return {id: storedId}; } diff --git a/modules/mgidBidAdapter.js b/modules/mgidBidAdapter.js index 3b45c1e69a5..c811a0b2981 100644 --- a/modules/mgidBidAdapter.js +++ b/modules/mgidBidAdapter.js @@ -1,5 +1,5 @@ +import { _each, deepAccess, isPlainObject, isArray, isStr, logInfo, parseUrl, isEmpty, triggerPixel, logWarn, getBidIdParameter, isFn, isNumber } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import {BANNER, NATIVE} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -58,9 +58,9 @@ let _NATIVE_ASSET_ID_TO_KEY_MAP = {}; let _NATIVE_ASSET_KEY_TO_ASSET_MAP = {}; // loading _NATIVE_ASSET_ID_TO_KEY_MAP -utils._each(NATIVE_ASSETS, anAsset => { _NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); +_each(NATIVE_ASSETS, anAsset => { _NATIVE_ASSET_ID_TO_KEY_MAP[anAsset.ID] = anAsset.KEY }); // loading _NATIVE_ASSET_KEY_TO_ASSET_MAP -utils._each(NATIVE_ASSETS, anAsset => { _NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); +_each(NATIVE_ASSETS, anAsset => { _NATIVE_ASSET_KEY_TO_ASSET_MAP[anAsset.KEY] = anAsset }); export const spec = { VERSION: '1.5', @@ -76,20 +76,20 @@ export const spec = { * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: (bid) => { - const banner = utils.deepAccess(bid, 'mediaTypes.banner'); - const native = utils.deepAccess(bid, 'mediaTypes.native'); - let nativeOk = utils.isPlainObject(native); + const banner = deepAccess(bid, 'mediaTypes.banner'); + const native = deepAccess(bid, 'mediaTypes.native'); + let nativeOk = isPlainObject(native); if (nativeOk) { - const nativeParams = utils.deepAccess(bid, 'nativeParams'); + const nativeParams = deepAccess(bid, 'nativeParams'); let assetsCount = 0; - if (utils.isPlainObject(nativeParams)) { + if (isPlainObject(nativeParams)) { for (let k in nativeParams) { let v = nativeParams[k]; const supportProp = spec.NATIVE_ASSET_KEY_TO_ASSET_MAP.hasOwnProperty(k); if (supportProp) { assetsCount++ } - if (!utils.isPlainObject(v) || (!supportProp && utils.deepAccess(v, 'required'))) { + if (!isPlainObject(v) || (!supportProp && deepAccess(v, 'required'))) { nativeOk = false; break; } @@ -97,17 +97,17 @@ export const spec = { } nativeOk = nativeOk && (assetsCount > 0); } - let bannerOk = utils.isPlainObject(banner); + let bannerOk = isPlainObject(banner); if (bannerOk) { - const sizes = utils.deepAccess(banner, 'sizes'); - bannerOk = utils.isArray(sizes) && sizes.length > 0; + const sizes = deepAccess(banner, 'sizes'); + bannerOk = isArray(sizes) && sizes.length > 0; for (let f = 0; bannerOk && f < sizes.length; f++) { bannerOk = sizes[f].length === 2; } } let acc = Number(bid.params.accountId); let plcmt = Number(bid.params.placementId); - return (bannerOk || nativeOk) && utils.isPlainObject(bid.params) && !!bid.adUnitCode && utils.isStr(bid.adUnitCode) && (plcmt > 0 ? bid.params.placementId.toString().search(spec.reId) === 0 : true) && + return (bannerOk || nativeOk) && isPlainObject(bid.params) && !!bid.adUnitCode && isStr(bid.adUnitCode) && (plcmt > 0 ? bid.params.placementId.toString().search(spec.reId) === 0 : true) && !!acc && acc > 0 && bid.params.accountId.toString().search(spec.reId) === 0; }, /** @@ -117,25 +117,25 @@ export const spec = { * @return ServerRequest Info describing the request to the server. */ buildRequests: (validBidRequests, bidderRequest) => { - utils.logInfo(LOG_INFO_PREFIX + `buildRequests`); + logInfo(LOG_INFO_PREFIX + `buildRequests`); if (validBidRequests.length === 0) { return; } const info = pageInfo(); - const page = info.location || utils.deepAccess(bidderRequest, 'refererInfo.referer') || utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl'); - const hostname = utils.parseUrl(page).hostname; + const page = info.location || deepAccess(bidderRequest, 'refererInfo.referer') || deepAccess(bidderRequest, 'refererInfo.canonicalUrl'); + const hostname = parseUrl(page).hostname; let domain = extractDomainFromHost(hostname) || hostname; const accountId = setOnAny(validBidRequests, 'params.accountId'); const muid = getLocalStorageSafely('mgMuidn'); let url = (setOnAny(validBidRequests, 'params.bidUrl') || ENDPOINT_URL) + accountId; - if (utils.isStr(muid) && muid.length > 0) { + if (isStr(muid) && muid.length > 0) { url += '?muid=' + muid; } const cur = setOnAny(validBidRequests, 'params.currency') || setOnAny(validBidRequests, 'params.cur') || config.getConfig('currency.adServerCurrency') || DEFAULT_CUR; const secure = window.location.protocol === 'https:' ? 1 : 0; let imp = []; validBidRequests.forEach(bid => { - let tagid = utils.deepAccess(bid, 'params.placementId') || 0; + let tagid = deepAccess(bid, 'params.placementId') || 0; tagid = !tagid ? bid.adUnitCode : tagid + '/' + bid.adUnitCode; let impObj = { id: bid.bidId, @@ -173,7 +173,7 @@ export const spec = { } let request = { - id: utils.deepAccess(bidderRequest, 'bidderRequestId'), + id: deepAccess(bidderRequest, 'bidderRequestId'), site: {domain, page}, cur: [cur], geo: {utcoffset: info.timeOffset}, @@ -195,7 +195,7 @@ export const spec = { if (info.referrer) { request.site.ref = info.referrer } - utils.logInfo(LOG_INFO_PREFIX + `buildRequest:`, request); + logInfo(LOG_INFO_PREFIX + `buildRequest:`, request); return { method: 'POST', url: url, @@ -209,36 +209,36 @@ export const spec = { * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse, bidRequests) => { - utils.logInfo(LOG_INFO_PREFIX + `interpretResponse`, serverResponse); - if (serverResponse == null || serverResponse.body == null || serverResponse.body === '' || !utils.isArray(serverResponse.body.seatbid) || !serverResponse.body.seatbid.length) { + logInfo(LOG_INFO_PREFIX + `interpretResponse`, serverResponse); + if (serverResponse == null || serverResponse.body == null || serverResponse.body === '' || !isArray(serverResponse.body.seatbid) || !serverResponse.body.seatbid.length) { return; } const returnedBids = []; - const muidn = utils.deepAccess(serverResponse.body, 'ext.muidn') - if (utils.isStr(muidn) && muidn.length > 0) { + const muidn = deepAccess(serverResponse.body, 'ext.muidn') + if (isStr(muidn) && muidn.length > 0) { setLocalStorageSafely('mgMuidn', muidn) } serverResponse.body.seatbid.forEach((bids) => { bids.bid.forEach((bid) => { const pbid = prebidBid(bid, serverResponse.body.cur); - if (pbid.mediaType === NATIVE && utils.isEmpty(pbid.native)) { + if (pbid.mediaType === NATIVE && isEmpty(pbid.native)) { return; } returnedBids.push(pbid); }) }); - utils.logInfo(LOG_INFO_PREFIX + `interpretedResponse`, returnedBids); + logInfo(LOG_INFO_PREFIX + `interpretedResponse`, returnedBids); return returnedBids; }, onBidWon: (bid) => { - const cpm = utils.deepAccess(bid, 'adserverTargeting.hb_pb') || ''; - if (utils.isStr(bid.nurl) && bid.nurl !== '') { + const cpm = deepAccess(bid, 'adserverTargeting.hb_pb') || ''; + if (isStr(bid.nurl) && bid.nurl !== '') { bid.nurl = bid.nurl.replace( /\${AUCTION_PRICE}/, cpm ); - utils.triggerPixel(bid.nurl); + triggerPixel(bid.nurl); } if (bid.isBurl) { if (bid.mediaType === BANNER) { @@ -251,13 +251,13 @@ export const spec = { /\${AUCTION_PRICE}/, cpm ); - utils.triggerPixel(bid.burl); + triggerPixel(bid.burl); } } - utils.logInfo(LOG_INFO_PREFIX + `onBidWon`); + logInfo(LOG_INFO_PREFIX + `onBidWon`); }, getUserSyncs: (syncOptions, serverResponses) => { - utils.logInfo(LOG_INFO_PREFIX + `getUserSyncs`); + logInfo(LOG_INFO_PREFIX + `getUserSyncs`); } }; @@ -265,7 +265,7 @@ registerBidder(spec); function setOnAny(collection, key) { for (let i = 0, result; i < collection.length; i++) { - result = utils.deepAccess(collection[i], key); + result = deepAccess(collection[i], key); if (result) { return result; } @@ -278,7 +278,7 @@ function setOnAny(collection, key) { * @return Bid */ function prebidBid(serverBid, cur) { - if (!utils.isStr(cur) || cur === '') { + if (!isStr(cur) || cur === '') { cur = DEFAULT_CUR; } const bid = { @@ -295,8 +295,8 @@ function prebidBid(serverBid, cur) { ttl: serverBid.ttl || 300, nurl: serverBid.nurl || '', burl: serverBid.burl || '', - isBurl: utils.isStr(serverBid.burl) && serverBid.burl.length > 0, - meta: { advertiserDomains: (utils.isArray(serverBid.adomain) && serverBid.adomain.length > 0 ? serverBid.adomain : []) }, + isBurl: isStr(serverBid.burl) && serverBid.burl.length > 0, + meta: { advertiserDomains: (isArray(serverBid.adomain) && serverBid.adomain.length > 0 ? serverBid.adomain : []) }, }; setMediaType(serverBid, bid); switch (bid.mediaType) { @@ -310,7 +310,7 @@ function prebidBid(serverBid, cur) { } function setMediaType(bid, newBid) { - if (utils.deepAccess(bid, 'ext.crtype') === 'native') { + if (deepAccess(bid, 'ext.crtype') === 'native') { newBid.mediaType = NATIVE; } else { newBid.mediaType = BANNER; @@ -364,7 +364,7 @@ function setLocalStorageSafely(key, val) { } function createBannerRequest(bid) { - const sizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); + const sizes = deepAccess(bid, 'mediaTypes.banner.sizes'); let format = []; if (sizes.length > 1) { for (let f = 0; f < sizes.length; f++) { @@ -380,7 +380,7 @@ function createBannerRequest(bid) { if (format.length) { r.format = format } - const pos = utils.deepAccess(bid, 'mediaTypes.banner.pos') || 0 + const pos = deepAccess(bid, 'mediaTypes.banner.pos') || 0 if (pos) { r.pos = pos } @@ -407,15 +407,15 @@ function createNativeRequest(params) { }; break; case NATIVE_ASSETS.IMAGE.KEY: - const wmin = params[key].wmin || params[key].minimumWidth || (utils.isArray(params[key].minsizes) && params[key].minsizes.length > 0 ? params[key].minsizes[0] : 0); - const hmin = params[key].hmin || params[key].minimumHeight || (utils.isArray(params[key].minsizes) && params[key].minsizes.length > 1 ? params[key].minsizes[1] : 0); + const wmin = params[key].wmin || params[key].minimumWidth || (isArray(params[key].minsizes) && params[key].minsizes.length > 0 ? params[key].minsizes[0] : 0); + const hmin = params[key].hmin || params[key].minimumHeight || (isArray(params[key].minsizes) && params[key].minsizes.length > 1 ? params[key].minsizes[1] : 0); assetObj = { id: NATIVE_ASSETS.IMAGE.ID, required: params[key].required ? 1 : 0, img: { type: NATIVE_ASSET_IMAGE_TYPE.IMAGE, - w: params[key].w || params[key].width || (utils.isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[0] : 0), - h: params[key].h || params[key].height || (utils.isArray(params[key].sizes) && params[key].sizes.length > 1 ? params[key].sizes[1] : 0), + w: params[key].w || params[key].width || (isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[0] : 0), + h: params[key].h || params[key].height || (isArray(params[key].sizes) && params[key].sizes.length > 1 ? params[key].sizes[1] : 0), mimes: params[key].mimes, ext: params[key].ext, } @@ -439,8 +439,8 @@ function createNativeRequest(params) { required: params[key].required ? 1 : 0, img: { type: NATIVE_ASSET_IMAGE_TYPE.ICON, - w: params[key].w || params[key].width || (utils.isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[0] : 0), - h: params[key].h || params[key].height || (utils.isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[1] : 0), + w: params[key].w || params[key].width || (isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[0] : 0), + h: params[key].h || params[key].height || (isArray(params[key].sizes) && params[key].sizes.length > 0 ? params[key].sizes[1] : 0), } }; if (!assetObj.img.w) { @@ -485,7 +485,7 @@ function createNativeRequest(params) { break; } else { if (ele.id === 4 && nativeRequestObject.assets[i].id === 11) { - if (utils.deepAccess(nativeRequestObject.assets[i], 'data.type') === ele.data.type) { + if (deepAccess(nativeRequestObject.assets[i], 'data.type') === ele.data.type) { presentrequiredAssetCount++; break; } @@ -517,7 +517,7 @@ function parseNativeResponse(bid, newBid) { try { adm = JSON.parse(bid.adm); } catch (ex) { - utils.logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native response for ad response: ' + newBid.adm); + logWarn(LOG_WARN_PREFIX + 'Error: Cannot parse native response for ad response: ' + newBid.adm); return; } if (adm && adm.native && adm.native.assets && adm.native.assets.length > 0) { @@ -591,16 +591,16 @@ function pageInfo() { * @returns {*|number} floor price */ function getBidFloor(bid, cur) { - let bidFloor = utils.getBidIdParameter('bidfloor', bid.params) || utils.getBidIdParameter('bidFloor', bid.params) || 0; + let bidFloor = getBidIdParameter('bidfloor', bid.params) || getBidIdParameter('bidFloor', bid.params) || 0; const reqCur = cur - if (!bidFloor && utils.isFn(bid.getFloor)) { + if (!bidFloor && isFn(bid.getFloor)) { const floorObj = bid.getFloor({ currency: '*', mediaType: '*', size: '*' }); - if (utils.isPlainObject(floorObj) && utils.isNumber(floorObj.floor)) { + if (isPlainObject(floorObj) && isNumber(floorObj.floor)) { if (!floorObj.currency && reqCur !== DEFAULT_CUR) { floorObj.currency = DEFAULT_CUR } diff --git a/modules/microadBidAdapter.js b/modules/microadBidAdapter.js index c78a66aecee..982bd61840a 100644 --- a/modules/microadBidAdapter.js +++ b/modules/microadBidAdapter.js @@ -1,6 +1,6 @@ +import { deepAccess, isEmpty, isStr } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'microad'; @@ -82,8 +82,8 @@ export const spec = { } } - const idlEnv = utils.deepAccess(bid, 'userId.idl_env') - if (!utils.isEmpty(idlEnv) && utils.isStr(idlEnv)) { + const idlEnv = deepAccess(bid, 'userId.idl_env') + if (!isEmpty(idlEnv) && isStr(idlEnv)) { params['idl_env'] = idlEnv } diff --git a/modules/mwOpenLinkIdSystem.js b/modules/mwOpenLinkIdSystem.js index b2381836d5d..552223fa73c 100644 --- a/modules/mwOpenLinkIdSystem.js +++ b/modules/mwOpenLinkIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; +import { timestamp, logError, deepClone, generateUUID, isPlainObject } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -18,20 +18,20 @@ const openLinkID = { const storage = getStorageManager(); function getExpirationDate() { - return (new Date(utils.timestamp() + openLinkID.cookie_expiration)).toGMTString(); + return (new Date(timestamp() + openLinkID.cookie_expiration)).toGMTString(); } function isValidConfig(configParams) { if (!configParams) { - utils.logError('User ID - mwOlId submodule requires configParams'); + logError('User ID - mwOlId submodule requires configParams'); return false; } if (!configParams.accountId) { - utils.logError('User ID - mwOlId submodule requires accountId to be defined'); + logError('User ID - mwOlId submodule requires accountId to be defined'); return false; } if (!configParams.partnerId) { - utils.logError('User ID - mwOlId submodule requires partnerId to be defined'); + logError('User ID - mwOlId submodule requires partnerId to be defined'); return false; } return true; @@ -96,7 +96,7 @@ function register(configParams, olid) { function setID(configParams) { if (!isValidConfig(configParams)) return undefined; const mwOlId = readCookie(); - const newMwOlId = mwOlId ? utils.deepClone(mwOlId) : {eid: utils.generateUUID()}; + const newMwOlId = mwOlId ? deepClone(mwOlId) : {eid: generateUUID()}; writeCookie(newMwOlId); register(configParams, newMwOlId.eid); return { @@ -122,7 +122,7 @@ export const mwOpenLinkIdSubModule = { * @return {(Object|undefined} */ decode(mwOlId) { - const id = mwOlId && utils.isPlainObject(mwOlId) ? mwOlId.eid : undefined; + const id = mwOlId && isPlainObject(mwOlId) ? mwOlId.eid : undefined; return id ? { 'mwOpenLinkId': id } : undefined; }, diff --git a/modules/nativoBidAdapter.js b/modules/nativoBidAdapter.js index 2f63dcb45f8..f91a8b6085b 100644 --- a/modules/nativoBidAdapter.js +++ b/modules/nativoBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isEmpty } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; // import { config } from 'src/config' @@ -120,7 +120,7 @@ export const spec = { */ interpretResponse: function (response, request) { // If the bid response was empty, return [] - if (!response || !response.body || utils.isEmpty(response.body)) return [] + if (!response || !response.body || isEmpty(response.body)) return [] try { const body = @@ -216,7 +216,7 @@ export const spec = { let body serverResponses.forEach((response) => { // If the bid response was empty, return [] - if (!response || !response.body || utils.isEmpty(response.body)) { + if (!response || !response.body || isEmpty(response.body)) { return syncs } diff --git a/modules/naveggIdSystem.js b/modules/naveggIdSystem.js index c37530b4151..7bd86879e9d 100644 --- a/modules/naveggIdSystem.js +++ b/modules/naveggIdSystem.js @@ -4,7 +4,7 @@ * @module modules/naveggId * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { isStr, isPlainObject, logError } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -58,7 +58,7 @@ export const naveggIdSubmodule = { * @return { Object | string | undefined } */ decode(value) { - const naveggIdVal = value ? utils.isStr(value) ? value : utils.isPlainObject(value) ? value.id : undefined : undefined; + const naveggIdVal = value ? isStr(value) ? value : isPlainObject(value) ? value.id : undefined : undefined; return naveggIdVal ? { 'naveggId': naveggIdVal } : undefined; @@ -81,7 +81,7 @@ export const naveggIdSubmodule = { try { return { id: naveggIdString }; } catch (error) { - utils.logError(error); + logError(error); } } return undefined; diff --git a/modules/nextMillenniumBidAdapter.js b/modules/nextMillenniumBidAdapter.js index 2101bb34e2b..d275fbf1160 100644 --- a/modules/nextMillenniumBidAdapter.js +++ b/modules/nextMillenniumBidAdapter.js @@ -1,5 +1,5 @@ +import { isStr, _each, getBidIdParameter } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import { BANNER } from '../src/mediaTypes.js'; const BIDDER_CODE = 'nextMillennium'; @@ -12,20 +12,20 @@ export const spec = { isBidRequestValid: function(bid) { return !!( - bid.params.placement_id && utils.isStr(bid.params.placement_id) + bid.params.placement_id && isStr(bid.params.placement_id) ); }, buildRequests: function(validBidRequests, bidderRequest) { const requests = []; - utils._each(validBidRequests, function(bid) { + _each(validBidRequests, function(bid) { const postBody = { 'id': bid.auctionId, 'ext': { 'prebid': { 'storedrequest': { - 'id': utils.getBidIdParameter('placement_id', bid.params) + 'id': getBidIdParameter('placement_id', bid.params) } } } @@ -60,8 +60,8 @@ export const spec = { const response = serverResponse.body; const bidResponses = []; - utils._each(response.seatbid, (resp) => { - utils._each(resp.bid, (bid) => { + _each(response.seatbid, (resp) => { + _each(resp.bid, (bid) => { bidResponses.push({ requestId: bidRequest.bidId, cpm: bid.price, diff --git a/modules/nobidBidAdapter.js b/modules/nobidBidAdapter.js index 619b46ecd1f..5c017852d3e 100644 --- a/modules/nobidBidAdapter.js +++ b/modules/nobidBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logInfo, deepAccess, logWarn, isArray, getParameterByName } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -14,7 +14,7 @@ window.nobid.timeoutTotal = 0; window.nobid.bidWonTotal = 0; window.nobid.refreshCount = 0; function log(msg, obj) { - utils.logInfo('-NoBid- ' + msg, obj) + logInfo('-NoBid- ' + msg, obj) } function nobidSetCookie(cname, cvalue, hours) { var d = new Date(); @@ -29,7 +29,7 @@ function nobidHasPurpose1Consent(bidderRequest) { let result = true; if (bidderRequest && bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.gdprApplies && bidderRequest.gdprConsent.apiVersion === 2) { - result = !!(utils.deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); + result = !!(deepAccess(bidderRequest.gdprConsent, 'vendorData.purpose.consents.1') === true); } } return result; @@ -112,11 +112,11 @@ function nobidBuildRequests(bids, bidderRequest) { var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); return `${width}x${height}`; } catch (e) { - utils.logWarn('Could not parse screen dimensions, error details:', e); + logWarn('Could not parse screen dimensions, error details:', e); } } var getEIDs = function(eids) { - if (utils.isArray(eids) && eids.length > 0) { + if (isArray(eids) && eids.length > 0) { let src = []; eids.forEach((eid) => { let ids = []; @@ -150,7 +150,7 @@ function nobidBuildRequests(bids, bidderRequest) { if (sch) state['schain'] = sch; const cop = coppa(); if (cop) state['coppa'] = cop; - const eids = getEIDs(utils.deepAccess(bids, '0.userIdAsEids')); + const eids = getEIDs(deepAccess(bids, '0.userIdAsEids')); if (eids && eids.length > 0) state['eids'] = eids; return state; } @@ -228,8 +228,8 @@ function nobidBuildRequests(bids, bidderRequest) { var placementId = bid.params['placementId']; var adType = 'banner'; - const videoMediaType = utils.deepAccess(bid, 'mediaTypes.video'); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, 'mediaTypes.video'); + const context = deepAccess(bid, 'mediaTypes.video.context'); if (bid.mediaType === VIDEO || (videoMediaType && (context === 'instream' || context === 'outstream'))) { adType = 'video'; } @@ -363,7 +363,7 @@ export const spec = { buildRequests: function(validBidRequests, bidderRequest) { function resolveEndpoint() { var ret = 'https://ads.servenobid.com/'; - var env = (typeof utils.getParameterByName === 'function') && (utils.getParameterByName('nobid-env')); + var env = (typeof getParameterByName === 'function') && (getParameterByName('nobid-env')); if (!env) ret = 'https://ads.servenobid.com/'; else if (env == 'beta') ret = 'https://beta.servenobid.com/'; else if (env == 'dev') ret = '//localhost:8282/'; @@ -448,7 +448,7 @@ export const spec = { } return syncs; } else { - utils.logWarn('-NoBid- Please enable iframe based user sync.', syncOptions); + logWarn('-NoBid- Please enable iframe based user sync.', syncOptions); return []; } }, diff --git a/modules/novatiqIdSystem.js b/modules/novatiqIdSystem.js index fbfa6ca8abc..4c3324d3fc0 100644 --- a/modules/novatiqIdSystem.js +++ b/modules/novatiqIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js'; +import { logInfo } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; @@ -47,22 +47,22 @@ export const novatiqIdSubmodule = { const configParams = config.params || {}; const srcId = this.getSrcId(configParams); - utils.logInfo('NOVATIQ Sync request used sourceid param: ' + srcId); + logInfo('NOVATIQ Sync request used sourceid param: ' + srcId); let partnerhost; partnerhost = window.location.hostname; - utils.logInfo('NOVATIQ partner hostname: ' + partnerhost); + logInfo('NOVATIQ partner hostname: ' + partnerhost); const novatiqId = snowflakeId(); const url = 'https://spadsync.com/sync?sptoken=' + novatiqId + '&sspid=' + srcId + '&ssphost=' + partnerhost; ajax(url, undefined, undefined, { method: 'GET', withCredentials: false }); - utils.logInfo('NOVATIQ snowflake: ' + novatiqId); + logInfo('NOVATIQ snowflake: ' + novatiqId); return { 'id': novatiqId } }, getSrcId(configParams) { - utils.logInfo('NOVATIQ Configured sourceid param: ' + configParams.sourceid); + logInfo('NOVATIQ Configured sourceid param: ' + configParams.sourceid); function isHex(str) { var a = parseInt(str, 16); @@ -72,13 +72,13 @@ export const novatiqIdSubmodule = { let srcId; if (typeof configParams.sourceid === 'undefined' || configParams.sourceid === null || configParams.sourceid === '') { srcId = '000'; - utils.logInfo('NOVATIQ sourceid param set to value 000 due to undefined parameter or missing value in config section'); + logInfo('NOVATIQ sourceid param set to value 000 due to undefined parameter or missing value in config section'); } else if (configParams.sourceid.length < 3 || configParams.sourceid.length > 3) { srcId = '001'; - utils.logInfo('NOVATIQ sourceid param set to value 001 due to wrong size in config section 3 chars max e.g. 1ab'); + logInfo('NOVATIQ sourceid param set to value 001 due to wrong size in config section 3 chars max e.g. 1ab'); } else if (isHex(configParams.sourceid) == false) { srcId = '002'; - utils.logInfo('NOVATIQ sourceid param set to value 002 due to wrong format in config section expecting hex value only'); + logInfo('NOVATIQ sourceid param set to value 002 due to wrong format in config section expecting hex value only'); } else { srcId = configParams.sourceid; } diff --git a/modules/oneVideoBidAdapter.js b/modules/oneVideoBidAdapter.js index 880f4992614..e0db143dc0f 100644 --- a/modules/oneVideoBidAdapter.js +++ b/modules/oneVideoBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logError, logWarn, parseSizesInput, generateUUID, isFn, logMessage, isPlainObject, isStr, isNumber, isArray } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'oneVideo'; @@ -28,7 +28,7 @@ export const spec = { } // MediaTypes Video / Banner validation if (typeof bid.mediaTypes.video === 'undefined' && typeof bid.mediaTypes.banner === 'undefined') { - utils.logError('Failed validation: adUnit mediaTypes.video OR mediaTypes.banner not declared'); + logError('Failed validation: adUnit mediaTypes.video OR mediaTypes.banner not declared'); return false; }; @@ -36,27 +36,27 @@ export const spec = { // Player size validation if (typeof bid.mediaTypes.video.playerSize === 'undefined') { if (bid.params.video && (typeof bid.params.video.playerWidth === 'undefined' || typeof bid.params.video.playerHeight === 'undefined')) { - utils.logError('Failed validation: Player size not declared in either mediaTypes.playerSize OR bid.params.video.plauerWidth & bid.params.video.playerHeight.'); + logError('Failed validation: Player size not declared in either mediaTypes.playerSize OR bid.params.video.plauerWidth & bid.params.video.playerHeight.'); return false; }; }; // Mimes validation if (typeof bid.mediaTypes.video.mimes === 'undefined') { if (!bid.params.video || typeof bid.params.video.mimes === 'undefined') { - utils.logError('Failed validation: adUnit mediaTypes.mimes OR params.video.mimes not declared'); + logError('Failed validation: adUnit mediaTypes.mimes OR params.video.mimes not declared'); return false; }; }; // Prevend DAP Outstream validation, Banner DAP validation & Multi-Format adUnit support if (bid.mediaTypes.video.context === 'outstream' && bid.params.video && bid.params.video.display === 1) { - utils.logError('Failed validation: Dynamic Ad Placement cannot be used with context Outstream (params.video.display=1)'); + logError('Failed validation: Dynamic Ad Placement cannot be used with context Outstream (params.video.display=1)'); return false; }; }; // Publisher Id (Exchange) validation if (typeof bid.params.pubId === 'undefined') { - utils.logError('Failed validation: Adapter cannot send requests without bid.params.pubId'); + logError('Failed validation: Adapter cannot send requests without bid.params.pubId'); return false; } @@ -106,7 +106,7 @@ export const spec = { response = null; } if (!response || !bid || (!bid.adm && !bid.nurl) || !bid.price) { - utils.logWarn(`No valid bids from ${spec.code} bidder`); + logWarn(`No valid bids from ${spec.code} bidder`); return []; } size = getSize(bidRequest.sizes); @@ -172,7 +172,7 @@ export const spec = { }; function getSize(sizes) { - let parsedSizes = utils.parseSizesInput(sizes); + let parsedSizes = parseSizesInput(sizes); let [ width, height ] = parsedSizes.length ? parsedSizes[0].split('x') : []; return { width: parseInt(width, 10) || undefined, @@ -194,7 +194,7 @@ function getRequestData(bid, consentData, bidRequest) { size: '*' }; let bidData = { - id: utils.generateUUID(), + id: generateUUID(), at: 2, imp: [{ id: '1', @@ -286,7 +286,7 @@ function getRequestData(bid, consentData, bidRequest) { } } - if (utils.isFn(bid.getFloor)) { + if (isFn(bid.getFloor)) { let floorData = bid.getFloor(getFloorRequestObject); bidData.imp[0].bidfloor = floorData.floor; bidData.cur = floorData.currency; @@ -344,7 +344,7 @@ function getRequestData(bid, consentData, bidRequest) { } } if (bid.params.video.e2etest) { - utils.logMessage('E2E test mode enabled: \n The following parameters are being overridden by e2etest mode:\n* bidfloor:null\n* width:300\n* height:250\n* mimes: video/mp4, application/javascript\n* api:2\n* site.page/ref: verizonmedia.com\n* tmax:1000'); + logMessage('E2E test mode enabled: \n The following parameters are being overridden by e2etest mode:\n* bidfloor:null\n* width:300\n* height:250\n* mimes: video/mp4, application/javascript\n* api:2\n* site.page/ref: verizonmedia.com\n* tmax:1000'); bidData.imp[0].bidfloor = null; bidData.imp[0].video.w = 300; bidData.imp[0].video.h = 250; @@ -354,15 +354,15 @@ function getRequestData(bid, consentData, bidRequest) { bidData.site.ref = 'https://verizonmedia.com'; bidData.tmax = 1000; } - if (bid.params.video.custom && utils.isPlainObject(bid.params.video.custom)) { + if (bid.params.video.custom && isPlainObject(bid.params.video.custom)) { bidData.imp[0].ext.custom = {}; for (const key in bid.params.video.custom) { - if (utils.isStr(bid.params.video.custom[key]) || utils.isNumber(bid.params.video.custom[key])) { + if (isStr(bid.params.video.custom[key]) || isNumber(bid.params.video.custom[key])) { bidData.imp[0].ext.custom[key] = bid.params.video.custom[key]; } } } - if (bid.params.video.content && utils.isPlainObject(bid.params.video.content)) { + if (bid.params.video.content && isPlainObject(bid.params.video.content)) { bidData.site.content = {}; const contentStringKeys = ['id', 'title', 'series', 'season', 'genre', 'contentrating', 'language']; const contentNumberkeys = ['episode', 'prodq', 'context', 'livestream', 'len']; @@ -370,14 +370,14 @@ function getRequestData(bid, consentData, bidRequest) { const contentObjectKeys = ['ext']; for (const contentKey in bid.params.video.content) { if ( - (contentStringKeys.indexOf(contentKey) > -1 && utils.isStr(bid.params.video.content[contentKey])) || - (contentNumberkeys.indexOf(contentKey) > -1 && utils.isNumber(bid.params.video.content[contentKey])) || - (contentObjectKeys.indexOf(contentKey) > -1 && utils.isPlainObject(bid.params.video.content[contentKey])) || - (contentArrayKeys.indexOf(contentKey) > -1 && utils.isArray(bid.params.video.content[contentKey]) && - bid.params.video.content[contentKey].every(catStr => utils.isStr(catStr)))) { + (contentStringKeys.indexOf(contentKey) > -1 && isStr(bid.params.video.content[contentKey])) || + (contentNumberkeys.indexOf(contentKey) > -1 && isNumber(bid.params.video.content[contentKey])) || + (contentObjectKeys.indexOf(contentKey) > -1 && isPlainObject(bid.params.video.content[contentKey])) || + (contentArrayKeys.indexOf(contentKey) > -1 && isArray(bid.params.video.content[contentKey]) && + bid.params.video.content[contentKey].every(catStr => isStr(catStr)))) { bidData.site.content[contentKey] = bid.params.video.content[contentKey]; } else { - utils.logMessage('oneVideo bid adapter validation error: ', contentKey, ' is either not supported is OpenRTB V2.5 or value is undefined'); + logMessage('oneVideo bid adapter validation error: ', contentKey, ' is either not supported is OpenRTB V2.5 or value is undefined'); } } } diff --git a/modules/onomagicBidAdapter.js b/modules/onomagicBidAdapter.js index 548c0170c05..25b0f1a5934 100644 --- a/modules/onomagicBidAdapter.js +++ b/modules/onomagicBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { getBidIdParameter, _each, isArray, getWindowTop, getUniqueIdentifierStr, parseUrl, logError, logWarn, createTrackPixelHtml, getWindowSelf, isFn, isPlainObject } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; @@ -22,17 +22,17 @@ function buildRequests(bidReqs, bidderRequest) { referrer = bidderRequest.refererInfo.referer; } const onomagicImps = []; - const publisherId = utils.getBidIdParameter('publisherId', bidReqs[0].params); - utils._each(bidReqs, function (bid) { + const publisherId = getBidIdParameter('publisherId', bidReqs[0].params); + _each(bidReqs, function (bid) { let bidSizes = (bid.mediaTypes && bid.mediaTypes.banner && bid.mediaTypes.banner.sizes) || bid.sizes; - bidSizes = ((utils.isArray(bidSizes) && utils.isArray(bidSizes[0])) ? bidSizes : [bidSizes]); - bidSizes = bidSizes.filter(size => utils.isArray(size)); + bidSizes = ((isArray(bidSizes) && isArray(bidSizes[0])) ? bidSizes : [bidSizes]); + bidSizes = bidSizes.filter(size => isArray(size)); const processedSizes = bidSizes.map(size => ({w: parseInt(size[0], 10), h: parseInt(size[1], 10)})); const element = document.getElementById(bid.adUnitCode); const minSize = _getMinSize(processedSizes); const viewabilityAmount = _isViewabilityMeasurable(element) - ? _getViewability(element, utils.getWindowTop(), minSize) + ? _getViewability(element, getWindowTop(), minSize) : 'na'; const viewabilityAmountRounded = isNaN(viewabilityAmount) ? viewabilityAmount : Math.round(viewabilityAmount); @@ -53,10 +53,10 @@ function buildRequests(bidReqs, bidderRequest) { onomagicImps.push(imp); }); const onomagicBidReq = { - id: utils.getUniqueIdentifierStr(), + id: getUniqueIdentifierStr(), imp: onomagicImps, site: { - domain: utils.parseUrl(referrer).host, + domain: parseUrl(referrer).host, page: referrer, publisher: { id: publisherId @@ -77,7 +77,7 @@ function buildRequests(bidReqs, bidderRequest) { options: {contentType: 'text/plain', withCredentials: false} }; } catch (e) { - utils.logError(e, {bidReqs, bidderRequest}); + logError(e, {bidReqs, bidderRequest}); } } @@ -95,7 +95,7 @@ function isBidRequestValid(bid) { function interpretResponse(serverResponse) { if (!serverResponse.body || typeof serverResponse.body != 'object') { - utils.logWarn('Onomagic server returned empty/non-json response: ' + JSON.stringify(serverResponse.body)); + logWarn('Onomagic server returned empty/non-json response: ' + JSON.stringify(serverResponse.body)); return []; } const { body: {id, seatbid} } = serverResponse; @@ -126,7 +126,7 @@ function interpretResponse(serverResponse) { } return onomagicBidResponses; } catch (e) { - utils.logError(e, {id, seatbid}); + logError(e, {id, seatbid}); } } @@ -150,7 +150,7 @@ function _getDeviceType() { function _getAdMarkup(bid) { let adm = bid.adm; if ('nurl' in bid) { - adm += utils.createTrackPixelHtml(bid.nurl); + adm += createTrackPixelHtml(bid.nurl); } return adm; } @@ -160,14 +160,14 @@ function _isViewabilityMeasurable(element) { } function _getViewability(element, topWin, { w, h } = {}) { - return utils.getWindowTop().document.visibilityState === 'visible' + return getWindowTop().document.visibilityState === 'visible' ? _getPercentInView(element, topWin, { w, h }) : 0; } function _isIframe() { try { - return utils.getWindowSelf() !== utils.getWindowTop(); + return getWindowSelf() !== getWindowTop(); } catch (e) { return true; } @@ -247,7 +247,7 @@ function _getPercentInView(element, topWin, { w, h } = {}) { } function _getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return bid.params.bidFloor ? bid.params.bidFloor : null; } @@ -256,7 +256,7 @@ function _getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; From 384521ca46c5a43654f4a0bbbf35a6ea21dbdb88 Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 15:27:29 -0700 Subject: [PATCH 34/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7486) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module --- modules/instreamTracking.js | 10 +- modules/integr8BidAdapter.js | 8 +- modules/intentIqIdSystem.js | 14 +-- modules/interactiveOffersBidAdapter.js | 10 +- modules/invibesBidAdapter.js | 22 ++-- modules/invisiblyAnalyticsAdapter.js | 10 +- modules/iqmBidAdapter.js | 38 +++---- modules/iqzoneBidAdapter.js | 10 +- modules/ixBidAdapter.js | 144 ++++++++++++------------- modules/jixieBidAdapter.js | 12 +-- modules/kargoBidAdapter.js | 4 +- modules/kinessoIdSystem.js | 16 +-- modules/koblerBidAdapter.js | 24 ++--- modules/konduitAnalyticsAdapter.js | 8 +- modules/konduitWrapper.js | 28 ++--- 15 files changed, 179 insertions(+), 179 deletions(-) diff --git a/modules/instreamTracking.js b/modules/instreamTracking.js index 68bb4be79de..40a6ecb1939 100644 --- a/modules/instreamTracking.js +++ b/modules/instreamTracking.js @@ -1,8 +1,8 @@ +import { deepClone, getBidRequest, deepAccess } from '../src/utils.js'; import { config } from '../src/config.js'; import { auctionManager } from '../src/auctionManager.js'; import { INSTREAM } from '../src/video.js'; import * as events from '../src/events.js'; -import * as utils from '../src/utils.js'; import { BID_STATUS, EVENTS, TARGETING_KEYS } from '../src/constants.json'; const {CACHE_ID, UUID} = TARGETING_KEYS; @@ -17,7 +17,7 @@ const INSTREAM_TRACKING_DEFAULT_CONFIG = { // Set instreamTracking default values config.setDefaults({ - 'instreamTracking': utils.deepClone(INSTREAM_TRACKING_DEFAULT_CONFIG) + 'instreamTracking': deepClone(INSTREAM_TRACKING_DEFAULT_CONFIG) }); const whitelistedResources = /video|fetch|xmlhttprequest|other/; @@ -50,8 +50,8 @@ export function trackInstreamDeliveredImpressions({adUnits, bidsReceived, bidder // filter for video bids const instreamBids = bidsReceived.filter(bid => { - const bidderRequest = utils.getBidRequest(bid.requestId, bidderRequests); - return bidderRequest && utils.deepAccess(bidderRequest, 'mediaTypes.video.context') === INSTREAM && bid.videoCacheKey; + const bidderRequest = getBidRequest(bid.requestId, bidderRequests); + return bidderRequest && deepAccess(bidderRequest, 'mediaTypes.video.context') === INSTREAM && bid.videoCacheKey; }); if (!instreamBids.length) { return false; @@ -60,7 +60,7 @@ export function trackInstreamDeliveredImpressions({adUnits, bidsReceived, bidder // find unique instream ad units const instreamAdUnitMap = {}; adUnits.forEach(adUnit => { - if (!instreamAdUnitMap[adUnit.code] && utils.deepAccess(adUnit, 'mediaTypes.video.context') === INSTREAM) { + if (!instreamAdUnitMap[adUnit.code] && deepAccess(adUnit, 'mediaTypes.video.context') === INSTREAM) { instreamAdUnitMap[adUnit.code] = true; } }); diff --git a/modules/integr8BidAdapter.js b/modules/integr8BidAdapter.js index c5415951155..321c3c4c1ab 100644 --- a/modules/integr8BidAdapter.js +++ b/modules/integr8BidAdapter.js @@ -1,7 +1,7 @@ +import { deepAccess, isFn, isPlainObject } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'integr8'; const ENDPOINT_URL = 'https://integr8.central.gjirafa.tech/bid'; @@ -62,7 +62,7 @@ export const spec = { placementId: bidRequest.params.placementId, bidid: bidRequest.bidId, count: bidRequest.params.count, - skipTime: utils.deepAccess(bidRequest, 'mediaTypes.video.skipafter', bidRequest.params.skipTime), + skipTime: deepAccess(bidRequest, 'mediaTypes.video.skipafter', bidRequest.params.skipTime), floor: getBidFloor(bidRequest) }; }); @@ -130,7 +130,7 @@ function generateSizeParam(sizes) { } export function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return null; } @@ -140,7 +140,7 @@ export function getBidFloor(bid) { size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'EUR') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'EUR') { return floor.floor; } diff --git a/modules/intentIqIdSystem.js b/modules/intentIqIdSystem.js index e12a765c086..2092f9a185a 100644 --- a/modules/intentIqIdSystem.js +++ b/modules/intentIqIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logError, logInfo } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {submodule} from '../src/hook.js' import {getStorageManager} from '../src/storageManager.js'; @@ -47,7 +47,7 @@ export function readData(key) { return storage.getCookie(key); } } catch (error) { - utils.logError(error); + logError(error); } } @@ -59,7 +59,7 @@ export function readData(key) { */ function storeData(key, value) { try { - utils.logInfo(MODULE_NAME + ': storing data: key=' + key + ' value=' + value); + logInfo(MODULE_NAME + ': storing data: key=' + key + ' value=' + value); if (value) { if (storage.hasLocalStorage()) { @@ -71,7 +71,7 @@ function storeData(key, value) { } } } catch (error) { - utils.logError(error); + logError(error); } } @@ -84,7 +84,7 @@ function tryParse(data) { try { return JSON.parse(data); } catch (err) { - utils.logError(err); + logError(err); return null; } } @@ -114,7 +114,7 @@ export const intentIqIdSubmodule = { getId(config) { const configParams = (config && config.params) || {}; if (!configParams || typeof configParams.partner !== 'number') { - utils.logError('User ID - intentIqId submodule requires a valid partner to be defined'); + logError('User ID - intentIqId submodule requires a valid partner to be defined'); return; } @@ -155,7 +155,7 @@ export const intentIqIdSubmodule = { } }, error: error => { - utils.logError(MODULE_NAME + ': ID fetch encountered an error', error); + logError(MODULE_NAME + ': ID fetch encountered an error', error); callback(); } }; diff --git a/modules/interactiveOffersBidAdapter.js b/modules/interactiveOffersBidAdapter.js index 958c671e4b9..c1757198eca 100644 --- a/modules/interactiveOffersBidAdapter.js +++ b/modules/interactiveOffersBidAdapter.js @@ -1,7 +1,7 @@ +import { logWarn, isNumber } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER} from '../src/mediaTypes.js'; import {config} from '../src/config.js'; -import * as utils from '../src/utils.js'; const BIDDER_CODE = 'interactiveOffers'; const ENDPOINT = 'https://prebid.ioadx.com/bidRequest/?partnerId='; @@ -36,15 +36,15 @@ export const spec = { let ret = true; if (bid && bid.params) { if (!bid.params.partnerId) { - utils.logWarn('partnerId must be a valid ID'); + logWarn('partnerId must be a valid ID'); ret = false; } - if (bid.params.tmax && !utils.isNumber(bid.params.tmax)) { - utils.logWarn('tmax must be a valid numeric ID'); + if (bid.params.tmax && !isNumber(bid.params.tmax)) { + logWarn('tmax must be a valid numeric ID'); ret = false; } } else { - utils.logWarn('invalid request'); + logWarn('invalid request'); ret = false; } return ret; diff --git a/modules/invibesBidAdapter.js b/modules/invibesBidAdapter.js index 0441f712a2f..75da1509f19 100644 --- a/modules/invibesBidAdapter.js +++ b/modules/invibesBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logInfo } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {getStorageManager} from '../src/storageManager.js'; @@ -155,12 +155,12 @@ function buildRequest(bidRequests, bidderRequest) { function handleResponse(responseObj, bidRequests) { if (bidRequests == null || bidRequests.length === 0) { - utils.logInfo('Invibes Adapter - No bids have been requested'); + logInfo('Invibes Adapter - No bids have been requested'); return []; } if (!responseObj) { - utils.logInfo('Invibes Adapter - Bid response is empty'); + logInfo('Invibes Adapter - Bid response is empty'); return []; } @@ -171,7 +171,7 @@ function handleResponse(responseObj, bidRequests) { if (responseObj.MultipositionEnabled === true) { invibes.bidResponse.AdPlacements = invibes.bidResponse.AdPlacements.concat(responseObj.AdPlacements); } else { - utils.logInfo('Invibes Adapter - Bid response already received. Invibes only responds to one bid request per user visit'); + logInfo('Invibes Adapter - Bid response already received. Invibes only responds to one bid request per user visit'); return []; } } else { @@ -183,7 +183,7 @@ function handleResponse(responseObj, bidRequests) { let bidRequest = bidRequests[i]; if (invibes.placementBids.indexOf(bidRequest.params.placementId) > -1) { - utils.logInfo('Invibes Adapter - Placement was previously bid on ' + bidRequest.params.placementId); + logInfo('Invibes Adapter - Placement was previously bid on ' + bidRequest.params.placementId); continue; } @@ -215,7 +215,7 @@ function handleResponse(responseObj, bidRequests) { function createBid(bidRequest, requestPlacement, multipositionEnabled) { if (requestPlacement === null || requestPlacement.BidModel === null) { - utils.logInfo('Invibes Adapter - Placement not configured for bidding ' + bidRequest.params.placementId); + logInfo('Invibes Adapter - Placement not configured for bidding ' + bidRequest.params.placementId); return null; } @@ -223,10 +223,10 @@ function createBid(bidRequest, requestPlacement, multipositionEnabled) { let ads = requestPlacement.Ads; if (!Array.isArray(ads) || ads.length < 1) { if (requestPlacement.AdReason != null) { - utils.logInfo('Invibes Adapter - No ads ' + requestPlacement.AdReason); + logInfo('Invibes Adapter - No ads ' + requestPlacement.AdReason); } - utils.logInfo('Invibes Adapter - No ads available'); + logInfo('Invibes Adapter - No ads available'); return null; } @@ -241,7 +241,7 @@ function createBid(bidRequest, requestPlacement, multipositionEnabled) { }); if (blacklistsPushedCids) { - utils.logInfo('Invibes Adapter - Ad blacklists pushed ids'); + logInfo('Invibes Adapter - Ad blacklists pushed ids'); return null; } } @@ -250,7 +250,7 @@ function createBid(bidRequest, requestPlacement, multipositionEnabled) { return invibes.pushedCids[pushedCid].indexOf(ad.Cid) > -1; }); if (isBlacklisted) { - utils.logInfo('Invibes Adapter - Ad is blacklisted'); + logInfo('Invibes Adapter - Ad is blacklisted'); return null; } } @@ -258,7 +258,7 @@ function createBid(bidRequest, requestPlacement, multipositionEnabled) { invibes.pushedCids[ad.Cid] = ad.Blcids || []; const now = Date.now(); - utils.logInfo('Bid auction started at ' + bidModel.AuctionStartTime + ' . Invibes registered the bid at ' + now + ' ; bid request took a total of ' + (now - bidModel.AuctionStartTime) + ' ms.'); + logInfo('Bid auction started at ' + bidModel.AuctionStartTime + ' . Invibes registered the bid at ' + now + ' ; bid request took a total of ' + (now - bidModel.AuctionStartTime) + ' ms.'); return { requestId: bidRequest.bidId, diff --git a/modules/invisiblyAnalyticsAdapter.js b/modules/invisiblyAnalyticsAdapter.js index d4fd3831210..5d15ae55bfc 100644 --- a/modules/invisiblyAnalyticsAdapter.js +++ b/modules/invisiblyAnalyticsAdapter.js @@ -5,11 +5,11 @@ import { ajaxBuilder } from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; +import { generateUUID, logInfo } from '../src/utils.js'; + const DEFAULT_EVENT_URL = 'https://api.pymx5.com/v1/' + 'sites/events'; const analyticsType = 'endpoint'; const analyticsName = 'Invisibly Analytics Adapter:'; - -const utils = require('../src/utils.js'); const CONSTANTS = require('../src/constants.json'); const ajax = ajaxBuilder(0); @@ -33,7 +33,7 @@ const { } = CONSTANTS; const _VERSION = 1; -const _pageViewId = utils.generateUUID(); +const _pageViewId = generateUUID(); let initOptions = null; let _startAuction = 0; let _bidRequestTimeout = 0; @@ -122,7 +122,7 @@ function flush() { }; ajax( initOptions.url, - () => utils.logInfo(`${analyticsName} sent events batch`), + () => logInfo(`${analyticsName} sent events batch`), JSON.stringify(payload), { contentType: 'application/json', @@ -206,7 +206,7 @@ function handleEvent(eventType, eventArgs) { function sendEvent(event) { _eventQueue.push(event); - utils.logInfo(`${analyticsName}Event ${event.eventType}:`, event); + logInfo(`${analyticsName}Event ${event.eventType}:`, event); if (event.eventType === AUCTION_END) { flush(); diff --git a/modules/iqmBidAdapter.js b/modules/iqmBidAdapter.js index e7599fd54c0..75854d39fd5 100644 --- a/modules/iqmBidAdapter.js +++ b/modules/iqmBidAdapter.js @@ -1,6 +1,6 @@ +import { deepAccess, getBidIdParameter, isArray, _each, getWindowTop, parseUrl } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {config} from '../src/config.js'; -import * as utils from '../src/utils.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import {INSTREAM} from '../src/video.js'; @@ -28,11 +28,11 @@ export const spec = { * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bid) { - const banner = utils.deepAccess(bid, 'mediaTypes.banner'); - const videoMediaType = utils.deepAccess(bid, 'mediaTypes.video'); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const banner = deepAccess(bid, 'mediaTypes.banner'); + const videoMediaType = deepAccess(bid, 'mediaTypes.video'); + const context = deepAccess(bid, 'mediaTypes.video.context'); if ((videoMediaType && context === INSTREAM)) { - const videoBidderParams = utils.deepAccess(bid, 'params.video', {}); + const videoBidderParams = deepAccess(bid, 'params.video', {}); if (!Array.isArray(videoMediaType.playerSize)) { return false; @@ -85,7 +85,7 @@ export const spec = { buildRequests: function (validBidRequests, bidderRequest) { return validBidRequests.map(bid => { var finalRequest = {}; - let bidfloor = utils.getBidIdParameter('bidfloor', bid.params); + let bidfloor = getBidIdParameter('bidfloor', bid.params); const imp = { id: bid.bidId, @@ -95,10 +95,10 @@ export const spec = { displaymanagerver: VERSION, } - if (utils.deepAccess(bid, 'mediaTypes.banner')) { + if (deepAccess(bid, 'mediaTypes.banner')) { imp.banner = getSize(bid.sizes); imp.mediatype = 'banner'; - } else if (utils.deepAccess(bid, 'mediaTypes.video')) { + } else if (deepAccess(bid, 'mediaTypes.video')) { imp.video = _buildVideoORTB(bid); imp.mediatype = 'video'; } @@ -107,8 +107,8 @@ export const spec = { finalRequest = { sizes: bid.sizes, id: bid.bidId, - publisherId: utils.getBidIdParameter('publisherId', bid.params), - placementId: utils.getBidIdParameter('placementId', bid.params), + publisherId: getBidIdParameter('publisherId', bid.params), + placementId: getBidIdParameter('placementId', bid.params), device: device, site: site, imp: imp, @@ -138,9 +138,9 @@ export const spec = { interpretResponse: function (serverResponse, bidRequest) { const bidResponses = []; serverResponse = serverResponse.body; - if (serverResponse && utils.isArray(serverResponse.seatbid)) { - utils._each(serverResponse.seatbid, function (bidList) { - utils._each(bidList.bid, function (bid) { + if (serverResponse && isArray(serverResponse.seatbid)) { + _each(serverResponse.seatbid, function (bidList) { + _each(bidList.bid, function (bid) { const responseCPM = parseFloat(bid.price); if (responseCPM > 0.0 && bid.impid) { const bidResponse = { @@ -228,16 +228,16 @@ function getSite(bidderRequest) { const {refererInfo} = bidderRequest; if (canAccessTopWindow()) { - const wt = utils.getWindowTop(); + const wt = getWindowTop(); domain = wt.location.hostname; page = wt.location.href; referrer = wt.document.referrer || ''; } else if (refererInfo.reachedTop) { - const url = utils.parseUrl(refererInfo.referer); + const url = parseUrl(refererInfo.referer); domain = url.hostname; page = refererInfo.referer; } else if (refererInfo.stack && refererInfo.stack.length && refererInfo.stack[0]) { - const url = utils.parseUrl(refererInfo.stack[0]); + const url = parseUrl(refererInfo.stack[0]); domain = url.hostname; } @@ -251,7 +251,7 @@ function getSite(bidderRequest) { function canAccessTopWindow() { try { - if (utils.getWindowTop().location.href) { + if (getWindowTop().location.href) { return true; } } catch (error) { @@ -260,8 +260,8 @@ function canAccessTopWindow() { } function _buildVideoORTB(bidRequest) { - const videoAdUnit = utils.deepAccess(bidRequest, 'mediaTypes.video'); - const videoBidderParams = utils.deepAccess(bidRequest, 'params.video', {}); + const videoAdUnit = deepAccess(bidRequest, 'mediaTypes.video'); + const videoBidderParams = deepAccess(bidRequest, 'params.video', {}); const video = {} const videoParams = { diff --git a/modules/iqzoneBidAdapter.js b/modules/iqzoneBidAdapter.js index 77bdcc0188d..5268f8935be 100644 --- a/modules/iqzoneBidAdapter.js +++ b/modules/iqzoneBidAdapter.js @@ -1,6 +1,6 @@ +import { isFn, deepAccess, logMessage } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; const BIDDER_CODE = 'iqzone'; @@ -66,8 +66,8 @@ function getPlacementReqData(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { - return utils.deepAccess(bid, 'params.bidfloor', 0); + if (!isFn(bid.getFloor)) { + return deepAccess(bid, 'params.bidfloor', 0); } try { @@ -113,7 +113,7 @@ export const spec = { deviceHeight = winTop.screen.height; winLocation = winTop.location; } catch (e) { - utils.logMessage(e); + logMessage(e); winLocation = window.location; } @@ -122,7 +122,7 @@ export const spec = { try { refferLocation = refferUrl && new URL(refferUrl); } catch (e) { - utils.logMessage(e); + logMessage(e); } let location = refferLocation || winLocation; diff --git a/modules/ixBidAdapter.js b/modules/ixBidAdapter.js index 4ff84e7c104..cf551c4f3db 100644 --- a/modules/ixBidAdapter.js +++ b/modules/ixBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, parseGPTSingleSizeArray, inIframe, deepClone, logError, logWarn, isFn, contains, isInteger, isArray, deepSetValue, parseQueryStringParameters, isEmpty, mergeDeep, convertTypes } from '../src/utils.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; import find from 'core-js-pure/features/array/find.js'; @@ -83,17 +83,17 @@ const VIDEO_PARAMS_ALLOW_LIST = [ function bidToBannerImp(bid) { const imp = bidToImp(bid); imp.banner = {}; - const impSize = utils.deepAccess(bid, 'params.size'); + const impSize = deepAccess(bid, 'params.size'); if (impSize) { imp.banner.w = impSize[0]; imp.banner.h = impSize[1]; // populate sid with size if not id - if (!utils.deepAccess(imp, 'ext.sid')) { - imp.ext.sid = utils.parseGPTSingleSizeArray(impSize); + if (!deepAccess(imp, 'ext.sid')) { + imp.ext.sid = parseGPTSingleSizeArray(impSize); } } - imp.banner.topframe = utils.inIframe() ? 0 : 1; + imp.banner.topframe = inIframe() ? 0 : 1; _applyFloor(bid, imp, BANNER); @@ -108,14 +108,14 @@ function bidToBannerImp(bid) { */ function bidToVideoImp(bid) { const imp = bidToImp(bid); - const videoAdUnitRef = utils.deepAccess(bid, 'mediaTypes.video'); - const videoParamRef = utils.deepAccess(bid, 'params.video'); + const videoAdUnitRef = deepAccess(bid, 'mediaTypes.video'); + const videoParamRef = deepAccess(bid, 'params.video'); const videoParamErrors = checkVideoParams(videoAdUnitRef, videoParamRef); if (videoParamErrors.length) { return {}; } - imp.video = videoParamRef ? utils.deepClone(bid.params.video) : {}; + imp.video = videoParamRef ? deepClone(bid.params.video) : {}; // copy all video properties to imp object for (const adUnitProperty in videoAdUnitRef) { @@ -125,7 +125,7 @@ function bidToVideoImp(bid) { } if (imp.video.minduration > imp.video.maxduration) { - utils.logError(`IX Bid Adapter: video minduration [${imp.video.minduration}] cannot be greater than video maxduration [${imp.video.maxduration}]`); + logError(`IX Bid Adapter: video minduration [${imp.video.minduration}] cannot be greater than video maxduration [${imp.video.maxduration}]`); return {}; } @@ -138,21 +138,21 @@ function bidToVideoImp(bid) { } else if (context === OUTSTREAM) { imp.video.placement = 4; } else { - utils.logWarn(`IX Bid Adapter: Video context '${context}' is not supported`); + logWarn(`IX Bid Adapter: Video context '${context}' is not supported`); } } if (!(imp.video.w && imp.video.h)) { // Getting impression Size - const impSize = getFirstSize(utils.deepAccess(imp, 'video.playerSize')) || getFirstSize(utils.deepAccess(bid, 'params.size')); + const impSize = getFirstSize(deepAccess(imp, 'video.playerSize')) || getFirstSize(deepAccess(bid, 'params.size')); if (impSize) { imp.video.w = impSize[0]; imp.video.h = impSize[1]; - if (!(utils.deepAccess(imp, 'ext.sid'))) { - imp.ext.sid = utils.parseGPTSingleSizeArray(impSize); + if (!(deepAccess(imp, 'ext.sid'))) { + imp.ext.sid = parseGPTSingleSizeArray(impSize); } } else { - utils.logWarn('IX Bid Adapter: Video size is missing in [mediaTypes.video] missing'); + logWarn('IX Bid Adapter: Video size is missing in [mediaTypes.video] missing'); return {}; } } @@ -180,7 +180,7 @@ function bidToImp(bid) { imp.ext.sid = String(bid.params.id); } - const dfpAdUnitCode = utils.deepAccess(bid, 'ortb2Imp.ext.data.adserver.adslot'); + const dfpAdUnitCode = deepAccess(bid, 'ortb2Imp.ext.data.adserver.adslot'); if (dfpAdUnitCode) { imp.ext.dfp_ad_unit_code = dfpAdUnitCode; } @@ -202,11 +202,11 @@ function _applyFloor(bid, imp, mediaType) { adapterFloor = { floor: bid.params.bidFloor, currency: bid.params.bidFloorCur }; } - if (utils.isFn(bid.getFloor)) { + if (isFn(bid.getFloor)) { let _mediaType = '*'; let _size = '*'; - if (mediaType && utils.contains(SUPPORTED_AD_TYPES, mediaType)) { + if (mediaType && contains(SUPPORTED_AD_TYPES, mediaType)) { const { w: width, h: height } = imp[mediaType]; _mediaType = mediaType; _size = [width, height]; @@ -218,7 +218,7 @@ function _applyFloor(bid, imp, mediaType) { }); } catch (err) { // continue with no module floors - utils.logWarn('priceFloors module call getFloor failed, error : ', err); + logWarn('priceFloors module call getFloor failed, error : ', err); } } @@ -243,8 +243,8 @@ function _applyFloor(bid, imp, mediaType) { */ function parseBid(rawBid, currency, bidRequest) { const bid = {}; - const isValidExpiry = !!((utils.deepAccess(rawBid, 'exp') && utils.isInteger(rawBid.exp))); - const dealID = utils.deepAccess(rawBid, 'dealid') || utils.deepAccess(rawBid, 'ext.dealid'); + const isValidExpiry = !!((deepAccess(rawBid, 'exp') && isInteger(rawBid.exp))); + const dealID = deepAccess(rawBid, 'dealid') || deepAccess(rawBid, 'ext.dealid'); if (PRICE_TO_DOLLAR_FACTOR.hasOwnProperty(currency)) { bid.cpm = rawBid.price / PRICE_TO_DOLLAR_FACTOR[currency]; @@ -263,7 +263,7 @@ function parseBid(rawBid, currency, bidRequest) { bid.creativeId = rawBid.hasOwnProperty('crid') ? rawBid.crid : '-'; // in the event of a video - if (utils.deepAccess(rawBid, 'ext.vasturl')) { + if (deepAccess(rawBid, 'ext.vasturl')) { bid.vastUrl = rawBid.ext.vasturl bid.width = bidRequest.video.w; bid.height = bidRequest.video.h; @@ -279,9 +279,9 @@ function parseBid(rawBid, currency, bidRequest) { } bid.meta = {}; - bid.meta.networkId = utils.deepAccess(rawBid, 'ext.dspid'); - bid.meta.brandId = utils.deepAccess(rawBid, 'ext.advbrandid'); - bid.meta.brandName = utils.deepAccess(rawBid, 'ext.advbrand'); + bid.meta.networkId = deepAccess(rawBid, 'ext.dspid'); + bid.meta.brandId = deepAccess(rawBid, 'ext.advbrandid'); + bid.meta.brandName = deepAccess(rawBid, 'ext.advbrand'); if (rawBid.adomain && rawBid.adomain.length > 0) { bid.meta.advertiserDomains = rawBid.adomain; } @@ -296,7 +296,7 @@ function parseBid(rawBid, currency, bidRequest) { * @return {boolean} True if this is a valid size format, and false otherwise. */ function isValidSize(size) { - return Array.isArray(size) && size.length === 2 && utils.isInteger(size[0]) && utils.isInteger(size[1]); + return Array.isArray(size) && size.length === 2 && isInteger(size[0]) && isInteger(size[1]); } /** @@ -330,7 +330,7 @@ function checkVideoParams(mediaTypeVideoRef, paramsVideoRef) { const errorList = []; if (!mediaTypeVideoRef) { - utils.logWarn('IX Bid Adapter: mediaTypes.video is the preferred location for video params in ad unit'); + logWarn('IX Bid Adapter: mediaTypes.video is the preferred location for video params in ad unit'); } for (let property of REQUIRED_VIDEO_PARAMS) { @@ -416,9 +416,9 @@ function getBidRequest(id, impressions, validBidRequests) { function getEidInfo(allEids, flocData) { let toSend = []; let seenSources = {}; - if (utils.isArray(allEids)) { + if (isArray(allEids)) { for (const eid of allEids) { - if (SOURCE_RTI_MAPPING[eid.source] && utils.deepAccess(eid, 'uids.0')) { + if (SOURCE_RTI_MAPPING[eid.source] && deepAccess(eid, 'uids.0')) { seenSources[eid.source] = true; eid.uids[0].ext = { rtiPartner: SOURCE_RTI_MAPPING[eid.source] @@ -454,7 +454,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { // Always use secure HTTPS protocol. let baseUrl = SECURE_BID_URL; // Get ids from Prebid User ID Modules - let eidInfo = getEidInfo(utils.deepAccess(validBidRequests, '0.userIdAsEids'), utils.deepAccess(validBidRequests, '0.userId.flocId')); + let eidInfo = getEidInfo(deepAccess(validBidRequests, '0.userIdAsEids'), deepAccess(validBidRequests, '0.userId.flocId')); let userEids = eidInfo.toSend; // RTI ids will be included in the bid request if the function getIdentityInfo() is loaded @@ -543,7 +543,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { } if (bidderRequest.uspConsent) { - utils.deepSetValue(r, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(r, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (bidderRequest.refererInfo) { @@ -552,7 +552,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { } if (config.getConfig('coppa')) { - utils.deepSetValue(r, 'regs.coppa', 1); + deepSetValue(r, 'regs.coppa', 1); } const payload = {}; @@ -572,10 +572,10 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { const requests = []; let requestSequenceNumber = 0; const transactionIds = Object.keys(impressions); - const baseRequestSize = `${baseUrl}${utils.parseQueryStringParameters({ ...payload, r: JSON.stringify(r) })}`.length; + const baseRequestSize = `${baseUrl}${parseQueryStringParameters({ ...payload, r: JSON.stringify(r) })}`.length; if (baseRequestSize > MAX_REQUEST_SIZE) { - utils.logError('ix bidder: Base request size has exceeded maximum request size.'); + logError('ix bidder: Base request size has exceeded maximum request size.'); return requests; } @@ -605,7 +605,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { } currentRequestSize += fpdRequestSize; } else { - utils.logError('ix bidder: IX config FPD request size has exceeded maximum request size.'); + logError('ix bidder: IX config FPD request size has exceeded maximum request size.'); } } @@ -673,7 +673,7 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { const fpd = config.getConfig('ortb2') || {}; - if (!utils.isEmpty(fpd) && !isFpdAdded) { + if (!isEmpty(fpd) && !isFpdAdded) { r.ext.ixdiag.fpd = true; const site = { ...(fpd.site || fpd.context) }; @@ -692,28 +692,28 @@ function buildRequest(validBidRequests, bidderRequest, impressions, version) { } }); - const clonedRObject = utils.deepClone(r); + const clonedRObject = deepClone(r); - clonedRObject.site = utils.mergeDeep({}, clonedRObject.site, site); - clonedRObject.user = utils.mergeDeep({}, clonedRObject.user, user); + clonedRObject.site = mergeDeep({}, clonedRObject.site, site); + clonedRObject.user = mergeDeep({}, clonedRObject.user, user); - const requestSize = `${baseUrl}${utils.parseQueryStringParameters({ ...payload, r: JSON.stringify(clonedRObject) })}`.length; + const requestSize = `${baseUrl}${parseQueryStringParameters({ ...payload, r: JSON.stringify(clonedRObject) })}`.length; if (requestSize < MAX_REQUEST_SIZE) { - r.site = utils.mergeDeep({}, r.site, site); - r.user = utils.mergeDeep({}, r.user, user); + r.site = mergeDeep({}, r.site, site); + r.user = mergeDeep({}, r.user, user); isFpdAdded = true; const fpdRequestSize = encodeURIComponent(JSON.stringify({ ...site, ...user })).length; currentRequestSize += fpdRequestSize; } else { - utils.logError('ix bidder: FPD request size has exceeded maximum request size.'); + logError('ix bidder: FPD request size has exceeded maximum request size.'); } } const isLastAdUnit = adUnitIndex === transactionIds.length - 1; if (wasAdUnitImpressionsTrimmed || isLastAdUnit) { - const clonedPayload = utils.deepClone(payload); + const clonedPayload = deepClone(payload); if (!isLastAdUnit || requestSequenceNumber) { r.ext.ixdiag.sn = requestSequenceNumber; clonedPayload.sn = requestSequenceNumber; @@ -778,30 +778,30 @@ function buildIXDiag(validBidRequests) { for (let i = 0; i < adUnitMap.length; i++) { var bid = validBidRequests.filter(bidRequest => bidRequest.transactionId === adUnitMap[i])[0]; - if (utils.deepAccess(bid, 'mediaTypes')) { + if (deepAccess(bid, 'mediaTypes')) { if (Object.keys(bid.mediaTypes).length > 1) { ixdiag.mfu++; } - if (utils.deepAccess(bid, 'mediaTypes.native')) { + if (deepAccess(bid, 'mediaTypes.native')) { ixdiag.nu++; } - if (utils.deepAccess(bid, 'mediaTypes.banner')) { + if (deepAccess(bid, 'mediaTypes.banner')) { ixdiag.bu++; } - if (utils.deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { + if (deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { ixdiag.ou++; // renderer only needed for outstream - const hasRenderer = typeof (utils.deepAccess(bid, 'renderer') || utils.deepAccess(bid, 'mediaTypes.video.renderer')) === 'object'; + const hasRenderer = typeof (deepAccess(bid, 'renderer') || deepAccess(bid, 'mediaTypes.video.renderer')) === 'object'; // if any one ad unit is missing renderer, set ren status to false in diag - ixdiag.ren = ixdiag.ren && hasRenderer ? (utils.deepAccess(ixdiag, 'ren')) : hasRenderer; + ixdiag.ren = ixdiag.ren && hasRenderer ? (deepAccess(ixdiag, 'ren')) : hasRenderer; } - if (utils.deepAccess(bid, 'mediaTypes.video.context') === 'instream') { + if (deepAccess(bid, 'mediaTypes.video.context') === 'instream') { ixdiag.iu++; } @@ -860,7 +860,7 @@ function createBannerImps(validBidRequest, missingBannerSizes, bannerImps) { let imp = bidToBannerImp(validBidRequest); - const bannerSizeDefined = includesSize(utils.deepAccess(validBidRequest, 'mediaTypes.banner.sizes'), utils.deepAccess(validBidRequest, 'params.size')); + const bannerSizeDefined = includesSize(deepAccess(validBidRequest, 'mediaTypes.banner.sizes'), deepAccess(validBidRequest, 'params.size')); // Create IX imps from params.size if (bannerSizeDefined) { @@ -884,7 +884,7 @@ function createBannerImps(validBidRequest, missingBannerSizes, bannerImps) { * @returns {string} */ function detectParamsType(validBidRequest) { - if (utils.deepAccess(validBidRequest, 'params.video') && utils.deepAccess(validBidRequest, 'mediaTypes.video')) { + if (deepAccess(validBidRequest, 'params.video') && deepAccess(validBidRequest, 'mediaTypes.video')) { return VIDEO; } @@ -909,8 +909,8 @@ function updateMissingSizes(validBidRequest, missingBannerSizes, imp) { missingBannerSizes[transactionID].missingSizes = currentSizeList; } else { // New Ad Unit - if (utils.deepAccess(validBidRequest, 'mediaTypes.banner.sizes')) { - let sizeList = utils.deepClone(validBidRequest.mediaTypes.banner.sizes); + if (deepAccess(validBidRequest, 'mediaTypes.banner.sizes')) { + let sizeList = deepClone(validBidRequest.mediaTypes.banner.sizes); removeFromSizes(sizeList, validBidRequest.params.size); let newAdUnitEntry = { 'missingSizes': sizeList, @@ -928,8 +928,8 @@ function updateMissingSizes(validBidRequest, missingBannerSizes, imp) { * @return {object} newImp Updated impression object */ function createMissingBannerImp(bid, imp, newSize) { - const newImp = utils.deepClone(imp); - newImp.ext.sid = utils.parseGPTSingleSizeArray(newSize); + const newImp = deepClone(imp); + newImp.ext.sid = parseGPTSingleSizeArray(newSize); newImp.banner.w = newSize[0]; newImp.banner.h = newSize[1]; @@ -969,7 +969,7 @@ function createRenderer (id) { try { renderer.setRender(outstreamRenderer); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; @@ -993,19 +993,19 @@ export const spec = { * @return {boolean} True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bid) { - const paramsVideoRef = utils.deepAccess(bid, 'params.video'); - const paramsSize = utils.deepAccess(bid, 'params.size'); - const mediaTypeBannerSizes = utils.deepAccess(bid, 'mediaTypes.banner.sizes'); - const mediaTypeVideoRef = utils.deepAccess(bid, 'mediaTypes.video'); - const mediaTypeVideoPlayerSize = utils.deepAccess(bid, 'mediaTypes.video.playerSize'); + const paramsVideoRef = deepAccess(bid, 'params.video'); + const paramsSize = deepAccess(bid, 'params.size'); + const mediaTypeBannerSizes = deepAccess(bid, 'mediaTypes.banner.sizes'); + const mediaTypeVideoRef = deepAccess(bid, 'mediaTypes.video'); + const mediaTypeVideoPlayerSize = deepAccess(bid, 'mediaTypes.video.playerSize'); const hasBidFloor = bid.params.hasOwnProperty('bidFloor'); const hasBidFloorCur = bid.params.hasOwnProperty('bidFloorCur'); - if (bid.hasOwnProperty('mediaType') && !(utils.contains(SUPPORTED_AD_TYPES, bid.mediaType))) { + if (bid.hasOwnProperty('mediaType') && !(contains(SUPPORTED_AD_TYPES, bid.mediaType))) { return false; } - if (utils.deepAccess(bid, 'mediaTypes.banner') && !mediaTypeBannerSizes) { + if (deepAccess(bid, 'mediaTypes.banner') && !mediaTypeBannerSizes) { return false; } @@ -1013,26 +1013,26 @@ export const spec = { // since there is an ix bidder level size, make sure its valid const ixSize = getFirstSize(paramsSize); if (!ixSize) { - utils.logError('ix bidder params: size has invalid format.'); + logError('ix bidder params: size has invalid format.'); return false; } // check if the ix bidder level size, is present in ad unit level if (!includesSize(bid.sizes, ixSize) && !(includesSize(mediaTypeVideoPlayerSize, ixSize)) && !(includesSize(mediaTypeBannerSizes, ixSize))) { - utils.logError('ix bidder params: bid size is not included in ad unit sizes or player size.'); + logError('ix bidder params: bid size is not included in ad unit sizes or player size.'); return false; } } if (typeof bid.params.siteId !== 'string' && typeof bid.params.siteId !== 'number') { - utils.logError('ix bidder params: siteId must be string or number value.'); + logError('ix bidder params: siteId must be string or number value.'); return false; } if (hasBidFloor || hasBidFloorCur) { if (!(hasBidFloor && hasBidFloorCur && isValidBidFloorParams(bid.params.bidFloor, bid.params.bidFloorCur))) { - utils.logError('ix bidder params: bidFloor / bidFloorCur parameter has invalid format.'); + logError('ix bidder params: bidFloor / bidFloorCur parameter has invalid format.'); return false; } } @@ -1041,7 +1041,7 @@ export const spec = { const errorList = checkVideoParams(mediaTypeVideoRef, paramsVideoRef); if (errorList.length) { errorList.forEach((err) => { - utils.logError(err); + logError(err); }); return false; } @@ -1065,7 +1065,7 @@ export const spec = { // Step 1: Create impresssions from IX params validBidRequests.forEach((validBidRequest) => { - const adUnitMediaTypes = Object.keys(utils.deepAccess(validBidRequest, 'mediaTypes', {})) + const adUnitMediaTypes = Object.keys(deepAccess(validBidRequest, 'mediaTypes', {})) switch (detectParamsType(validBidRequest)) { case BANNER: @@ -1156,7 +1156,7 @@ export const spec = { const bidRequest = getBidRequest(innerBids[j].impid, requestBid.imp, bidderRequest.validBidRequests); bid = parseBid(innerBids[j], responseBody.cur, bidRequest); - if (!utils.deepAccess(bid, 'mediaTypes.video.renderer') && utils.deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { + if (!deepAccess(bid, 'mediaTypes.video.renderer') && deepAccess(bid, 'mediaTypes.video.context') === 'outstream') { bid.mediaTypes.video.renderer = createRenderer(innerBids[j].bidId); } @@ -1174,7 +1174,7 @@ export const spec = { * @return {Object} params bid params */ transformBidParams: function (params, isOpenRtb) { - return utils.convertTypes({ + return convertTypes({ 'siteID': 'number' }, params); }, diff --git a/modules/jixieBidAdapter.js b/modules/jixieBidAdapter.js index db6c9032e65..0e05616465a 100644 --- a/modules/jixieBidAdapter.js +++ b/modules/jixieBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, parseUrl, deepAccess, isArray } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -95,7 +95,7 @@ function createRenderer_(bidAd, scriptUrl, createFcn) { try { renderer.setRender(createFcn); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; } @@ -110,7 +110,7 @@ function getMiscDims_() { let refererInfo_ = getRefererInfo(); let url_ = ((refererInfo_ && refererInfo_.referer) ? refererInfo_.referer : window.location.href); ret.pageurl = url_; - ret.domain = utils.parseUrl(url_).host; + ret.domain = parseUrl(url_).host; ret.device = getDevice_(); } catch (error) {} return ret; @@ -194,8 +194,8 @@ export const spec = { device: miscDims.device, pageurl: encodeURIComponent(miscDims.pageurl), domain: encodeURIComponent(miscDims.domain), - auctionid: utils.deepAccess(timeoutData, '0.auctionId'), - timeout: utils.deepAccess(timeoutData, '0.timeout'), + auctionid: deepAccess(timeoutData, '0.auctionId'), + timeout: deepAccess(timeoutData, '0.timeout'), count: timeoutData.length }); }, @@ -224,7 +224,7 @@ export const spec = { }, interpretResponse: function(response, bidRequest) { - if (response && response.body && utils.isArray(response.body.bids)) { + if (response && response.body && isArray(response.body.bids)) { const bidResponses = []; response.body.bids.forEach(function(oneBid) { let bnd = {}; diff --git a/modules/kargoBidAdapter.js b/modules/kargoBidAdapter.js index 610f4558139..895d8a7d259 100644 --- a/modules/kargoBidAdapter.js +++ b/modules/kargoBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { _each } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -28,7 +28,7 @@ export const spec = { const currency = (currencyObj && currencyObj.adServerCurrency) || 'USD'; const bidIds = {}; const bidSizes = {}; - utils._each(validBidRequests, bid => { + _each(validBidRequests, bid => { bidIds[bid.bidId] = bid.params.placementId; bidSizes[bid.bidId] = bid.sizes; }); diff --git a/modules/kinessoIdSystem.js b/modules/kinessoIdSystem.js index 2cd7f594dd2..ca8fe269a5e 100644 --- a/modules/kinessoIdSystem.js +++ b/modules/kinessoIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { logError, logInfo } from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {submodule} from '../src/hook.js'; import {coppaDataHandler, uspDataHandler} from '../src/adapterManager.js'; @@ -111,7 +111,7 @@ function encodeTime(now, len) { * @returns {Error} */ function createError(message) { - utils.logError(message); + logError(message); const err = new Error(message); err.source = 'kinessoId'; return err; @@ -147,10 +147,10 @@ function detectPrng(root) { function syncId(storedId) { return { success: function (responseBody) { - utils.logInfo('KinessoId: id to be synced: ' + storedId); + logInfo('KinessoId: id to be synced: ' + storedId); }, error: function () { - utils.logInfo('KinessoId: Sync error for id : ' + storedId); + logInfo('KinessoId: Sync error for id : ' + storedId); } } } @@ -165,7 +165,7 @@ function encodeId(value) { const knssoId = (value && typeof value === 'string') ? value : undefined; if (knssoId) { result.kpuid = knssoId; - utils.logInfo('KinessoId: Decoded value ' + JSON.stringify(result)); + logInfo('KinessoId: Decoded value ' + JSON.stringify(result)); return result; } return knssoId; @@ -217,17 +217,17 @@ export const kinessoIdSubmodule = { getId(config, consentData) { const configParams = (config && config.params) || {}; if (!configParams || typeof configParams.accountid !== 'number') { - utils.logError('User ID - KinessoId submodule requires a valid accountid to be defined'); + logError('User ID - KinessoId submodule requires a valid accountid to be defined'); return; } const coppa = coppaDataHandler.getCoppa(); if (coppa) { - utils.logInfo('KinessoId: IDs not provided for coppa requests, exiting KinessoId'); + logInfo('KinessoId: IDs not provided for coppa requests, exiting KinessoId'); return; } const accountId = configParams.accountid; const knnsoId = id(); - utils.logInfo('KinessoId: generated id ' + knnsoId); + logInfo('KinessoId: generated id ' + knnsoId); const kinessoIdPayload = {}; kinessoIdPayload.id = knnsoId; const payloadString = JSON.stringify(kinessoIdPayload); diff --git a/modules/koblerBidAdapter.js b/modules/koblerBidAdapter.js index 59d1639a329..49be80e969c 100644 --- a/modules/koblerBidAdapter.js +++ b/modules/koblerBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepAccess, isStr, replaceAuctionPrice, triggerPixel, isArray, parseQueryStringParameters, getWindowSelf } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER} from '../src/mediaTypes.js'; @@ -60,34 +60,34 @@ export const interpretResponse = function (serverResponse) { export const onBidWon = function (bid) { const cpm = bid.cpm || 0; const cpmCurrency = bid.currency || SUPPORTED_CURRENCY; - const adServerPrice = utils.deepAccess(bid, 'adserverTargeting.hb_pb', 0); + const adServerPrice = deepAccess(bid, 'adserverTargeting.hb_pb', 0); const adServerPriceCurrency = config.getConfig('currency.adServerCurrency') || SUPPORTED_CURRENCY; - if (utils.isStr(bid.nurl) && bid.nurl !== '') { - const winNotificationUrl = utils.replaceAuctionPrice(bid.nurl, cpm) + if (isStr(bid.nurl) && bid.nurl !== '') { + const winNotificationUrl = replaceAuctionPrice(bid.nurl, cpm) .replace(/\${AUCTION_PRICE_CURRENCY}/g, cpmCurrency) .replace(/\${AD_SERVER_PRICE}/g, adServerPrice) .replace(/\${AD_SERVER_PRICE_CURRENCY}/g, adServerPriceCurrency); - utils.triggerPixel(winNotificationUrl); + triggerPixel(winNotificationUrl); } }; export const onTimeout = function (timeoutDataArray) { - if (utils.isArray(timeoutDataArray)) { + if (isArray(timeoutDataArray)) { const refererInfo = getRefererInfo(); const pageUrl = (refererInfo && refererInfo.referer) ? refererInfo.referer : window.location.href; timeoutDataArray.forEach(timeoutData => { - const query = utils.parseQueryStringParameters({ + const query = parseQueryStringParameters({ ad_unit_code: timeoutData.adUnitCode, auction_id: timeoutData.auctionId, bid_id: timeoutData.bidId, timeout: timeoutData.timeout, - placement_id: utils.deepAccess(timeoutData, 'params.0.placementId'), + placement_id: deepAccess(timeoutData, 'params.0.placementId'), page_url: pageUrl, }); const timeoutNotificationUrl = `${TIMEOUT_NOTIFICATION_ENDPOINT}?${query}`; - utils.triggerPixel(timeoutNotificationUrl); + triggerPixel(timeoutNotificationUrl); }); } }; @@ -143,7 +143,7 @@ function buildOpenRtbImpObject(validBidRequest) { } function getDevice() { - const ws = utils.getWindowSelf(); + const ws = getWindowSelf(); const ua = ws.navigator.userAgent; if (/(tablet|ipad|playbook|silk|android 3.0|xoom|sch-i800|kindle)|(android(?!.*mobi))/i @@ -171,8 +171,8 @@ function getTest(validBidRequest) { } function getSizes(validBidRequest) { - const sizes = utils.deepAccess(validBidRequest, 'mediaTypes.banner.sizes', validBidRequest.sizes); - if (utils.isArray(sizes) && sizes.length > 0) { + const sizes = deepAccess(validBidRequest, 'mediaTypes.banner.sizes', validBidRequest.sizes); + if (isArray(sizes) && sizes.length > 0) { return sizes; } diff --git a/modules/konduitAnalyticsAdapter.js b/modules/konduitAnalyticsAdapter.js index f6b77f23d87..f8a44d7cc94 100644 --- a/modules/konduitAnalyticsAdapter.js +++ b/modules/konduitAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { parseSizesInput, logError, uniques } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; -import * as utils from '../src/utils.js'; import { targeting } from '../src/targeting.js'; import { config } from '../src/config.js'; import CONSTANTS from '../src/constants.json'; @@ -84,7 +84,7 @@ const konduitAnalyticsAdapter = Object.assign( ); function obtainBidTimeoutInfo (args) { - return args.map(item => item.bidder).filter(utils.uniques); + return args.map(item => item.bidder).filter(uniques); } function obtainAuctionInfo (auction) { @@ -109,7 +109,7 @@ function obtainBidRequestsInfo (bidRequests) { adUnitCode: bid.adUnitCode, bidId: bid.bidId, startTime: bid.startTime, - sizes: utils.parseSizesInput(bid.sizes).toString(), + sizes: parseSizesInput(bid.sizes).toString(), params: bid.params }; }), @@ -208,7 +208,7 @@ konduitAnalyticsAdapter.enableAnalytics = function (analyticsConfig) { const konduitId = config.getConfig('konduit.konduitId'); if (!konduitId) { - utils.logError('A konduitId in config is required to use konduitAnalyticsAdapter'); + logError('A konduitId in config is required to use konduitAnalyticsAdapter'); return; } diff --git a/modules/konduitWrapper.js b/modules/konduitWrapper.js index 3ce9bc7a501..f19318e3128 100644 --- a/modules/konduitWrapper.js +++ b/modules/konduitWrapper.js @@ -1,6 +1,6 @@ +import { logInfo, logError, isNumber, isStr, isEmpty } from '../src/utils.js'; import { registerVideoSupport } from '../src/adServerManager.js'; import { targeting } from '../src/targeting.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import { ajaxBuilder } from '../src/ajax.js'; import { getPriceBucketString } from '../src/cpmBucketManager.js'; @@ -49,12 +49,12 @@ function addLogLabel(args) { return args; } -function logInfo() { - utils.logInfo(...addLogLabel(arguments)); +function _logInfo() { + logInfo(...addLogLabel(arguments)); } -function logError() { - utils.logError(...addLogLabel(arguments)); +function _logError() { + logError(...addLogLabel(arguments)); } function sendRequest ({ host = SERVER_HOST, protocol = SERVER_PROTOCOL, method = 'GET', path, payload, callbacks, timeout }) { @@ -113,7 +113,7 @@ function setDefaultKCpmToBid(bid, winnerBid, priceGranularity) { } function addKCpmToBid(kCpm, bid, winnerBid, priceGranularity) { - if (utils.isNumber(kCpm)) { + if (isNumber(kCpm)) { bid.kCpm = kCpm; const priceStringsObj = getPriceBucketString( kCpm, @@ -134,7 +134,7 @@ function addKCpmToBid(kCpm, bid, winnerBid, priceGranularity) { } function addKonduitCacheKeyToBid(cacheKey, bid, winnerBid) { - if (utils.isStr(cacheKey)) { + if (isStr(cacheKey)) { bid.konduitCacheKey = cacheKey; if (config.getConfig(SEND_ALL_BIDS_CONFIG)) { @@ -163,7 +163,7 @@ export function processBids(options = {}) { options = options || {}; if (!konduitId) { - logError(errorMessages.NO_KONDUIT_ID); + _logError(errorMessages.NO_KONDUIT_ID); if (options.callback) { options.callback(new Error(errorMessages.NO_KONDUIT_ID), []); @@ -184,7 +184,7 @@ export function processBids(options = {}) { } if (!bids.length) { - logError(errorMessages.NO_BIDS); + _logError(errorMessages.NO_BIDS); if (options.callback) { options.callback(new Error(errorMessages.NO_BIDS), []); @@ -216,11 +216,11 @@ export function processBids(options = {}) { callbacks: { success: (data) => { let error = null; - logInfo('Bids processed successfully ', data); + _logInfo('Bids processed successfully ', data); try { const { kCpmData, cacheData } = JSON.parse(data); - if (utils.isEmpty(cacheData)) { + if (isEmpty(cacheData)) { throw new Error(errorMessages.CACHE_FAILURE); } @@ -234,7 +234,7 @@ export function processBids(options = {}) { }) } catch (err) { error = err; - logError('Error parsing JSON response for bidsProcessor data: ', err) + _logError('Error parsing JSON response for bidsProcessor data: ', err) } if (options.callback) { @@ -242,9 +242,9 @@ export function processBids(options = {}) { } }, error: (error) => { - logError('Bids were not processed successfully ', error); + _logError('Bids were not processed successfully ', error); if (options.callback) { - options.callback(utils.isStr(error) ? new Error(error) : error, bids); + options.callback(isStr(error) ? new Error(error) : error, bids); } } } From 5f45f957deddd4c12823597b45a828a7b783a6c6 Mon Sep 17 00:00:00 2001 From: Chris Huie Date: Tue, 28 Sep 2021 15:28:08 -0700 Subject: [PATCH 35/84] Fluct Bid Adapter: ie polyfill for url search params (#7478) * Fluct Bid Adapter: ie polyfill 4 url search params * more specific import * see if corejs is white listed * update to pure core js * update link * change format * add to whitelist * fix path to web * add features path * update path * drop web in path * fix path * try again * update to root * restore path * add comma --- allowedModules.js | 3 ++- modules/fluctBidAdapter.js | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/allowedModules.js b/allowedModules.js index 2d23b35c501..81920cdc15f 100644 --- a/allowedModules.js +++ b/allowedModules.js @@ -5,7 +5,8 @@ const sharedWhiteList = [ 'core-js-pure/features/set', // ie11 supports Set but not Set#values 'core-js-pure/features/string/includes', // no ie11 'core-js-pure/features/number/is-integer', // no ie11, - 'core-js-pure/features/array/from' // no ie11 + 'core-js-pure/features/array/from', // no ie11 + 'core-js-pure/web/url-search-params' // no ie11 ]; module.exports = { diff --git a/modules/fluctBidAdapter.js b/modules/fluctBidAdapter.js index 5d25043f1bf..57efaf2503f 100644 --- a/modules/fluctBidAdapter.js +++ b/modules/fluctBidAdapter.js @@ -1,5 +1,6 @@ import * as utils from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; +import URLSearchParams from 'core-js-pure/web/url-search-params' const BIDDER_CODE = 'fluct'; const END_POINT = 'https://hb.adingo.jp/prebid'; From d8282ecaa726a62b5a71b72b49394e7aa11409ae Mon Sep 17 00:00:00 2001 From: Harshad Mane Date: Tue, 28 Sep 2021 15:34:58 -0700 Subject: [PATCH 36/84] Multiple Bid/Analytics/ID/ other modules: import utils functions as needed and not the whole module (#7485) * added support for pubcommon, digitrust, id5id * added support for IdentityLink * changed the source for id5 * added unit test cases * changed source param for identityLink * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * Revert "import utils functions as needed and not the whole module" This reverts commit bc6c9f61f889e9aa2ef8ab207b87d4e7b49e3e57. * Revert "import utils functions as needed and not the whole module" This reverts commit ef500abb06648c763caa066ccd18fd5a18f2a1b5. * Revert "import utils functions as needed and not the whole module" This reverts commit 7e3fa3feba9ec9b8e81524419c3c13e94ee1049e. * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * import utils functions as needed and not the whole module * fix typo Co-authored-by: Chris Huie --- modules/growadvertisingBidAdapter.js | 15 +++--- modules/gumgumBidAdapter.js | 28 +++++------ modules/h12mediaBidAdapter.js | 24 +++++----- modules/haloIdSystem.js | 16 +++---- modules/hybridBidAdapter.js | 14 +++--- modules/iasRtdProvider.js | 14 +++--- modules/id5IdSystem.js | 48 +++++++++---------- modules/idImportLibrary.js | 70 +++++++++++++-------------- modules/idxIdSystem.js | 6 +-- modules/impactifyBidAdapter.js | 20 ++++---- modules/improvedigitalBidAdapter.js | 72 ++++++++++++++-------------- modules/imuIdSystem.js | 12 ++--- modules/inmarBidAdapter.js | 4 +- modules/innityBidAdapter.js | 6 +-- modules/inskinBidAdapter.js | 4 +- 15 files changed, 175 insertions(+), 178 deletions(-) diff --git a/modules/growadvertisingBidAdapter.js b/modules/growadvertisingBidAdapter.js index 0626b137a1b..286d27607c5 100644 --- a/modules/growadvertisingBidAdapter.js +++ b/modules/growadvertisingBidAdapter.js @@ -1,9 +1,8 @@ 'use strict'; -import * as utils from '../src/utils.js'; +import { getBidIdParameter, deepAccess, _each, triggerPixel } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER, NATIVE} from '../src/mediaTypes.js'; -import {triggerPixel} from '../src/utils.js'; const BIDDER_CODE = 'growads'; @@ -23,8 +22,8 @@ export const spec = { const zoneCounters = {}; return validBidRequests.map(bidRequest => { - zoneId = utils.getBidIdParameter('zoneId', bidRequest.params); - domain = utils.getBidIdParameter('domain', bidRequest.params); + zoneId = getBidIdParameter('zoneId', bidRequest.params); + domain = getBidIdParameter('domain', bidRequest.params); if (!(zoneId in zoneCounters)) { zoneCounters[zoneId] = 0; @@ -77,8 +76,8 @@ export const spec = { width = parseInt(response.width); height = parseInt(response.height); - minCPM = utils.getBidIdParameter('minCPM', request.params); - maxCPM = utils.getBidIdParameter('maxCPM', request.params); + minCPM = getBidIdParameter('minCPM', request.params); + maxCPM = getBidIdParameter('maxCPM', request.params); width = parseInt(response.width); height = parseInt(response.height); @@ -102,7 +101,7 @@ export const spec = { netRevenue: true, ttl: response.ttl, adUnitCode: request.adUnitCode, - referrer: utils.deepAccess(request, 'refererInfo.referer') + referrer: deepAccess(request, 'refererInfo.referer') }; if (response.hasOwnProperty(NATIVE)) { @@ -137,7 +136,7 @@ export const spec = { bid.ad = response.ad; bid.mediaType = BANNER; // Ensure that response ad matches one of the placement sizes. - utils._each(utils.deepAccess(request, 'mediaTypes.banner.sizes', []), function (size) { + _each(deepAccess(request, 'mediaTypes.banner.sizes', []), function (size) { if (width === size[0] && height === size[1]) { isCorrectSize = true; } diff --git a/modules/gumgumBidAdapter.js b/modules/gumgumBidAdapter.js index 0580675eed8..756d204e00d 100644 --- a/modules/gumgumBidAdapter.js +++ b/modules/gumgumBidAdapter.js @@ -1,7 +1,5 @@ -import * as utils from '../src/utils.js' - +import { logError, logWarn, parseSizesInput, _each, deepAccess } from '../src/utils.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; - import { config } from '../src/config.js' import { getStorageManager } from '../src/storageManager.js'; import includes from 'core-js-pure/features/array/includes'; @@ -51,7 +49,7 @@ function _getBrowserParams(topWindowUrl) { topScreen = topWindow.screen; topUrl = topWindowUrl || ''; } catch (error) { - utils.logError(error); + logError(error); return browserParams } @@ -131,7 +129,7 @@ function isBidRequestValid(bid) { const id = legacyParamID || params.slot || params.native || params.zone || params.pubID; if (invalidRequestIds[id]) { - utils.logWarn(`[GumGum] Please check the implementation for ${id} for the placement ${adUnitCode}`); + logWarn(`[GumGum] Please check the implementation for ${id} for the placement ${adUnitCode}`); return false; } @@ -146,12 +144,12 @@ function isBidRequestValid(bid) { case !!(params.inVideo): break; case !!(params.videoPubID): break; default: - utils.logWarn(`[GumGum] No product selected for the placement ${adUnitCode}, please check your implementation.`); + logWarn(`[GumGum] No product selected for the placement ${adUnitCode}, please check your implementation.`); return false; } if (params.bidfloor && !(typeof params.bidfloor === 'number' && isFinite(params.bidfloor))) { - utils.logWarn('[GumGum] bidfloor must be a Number'); + logWarn('[GumGum] bidfloor must be a Number'); return false; } @@ -173,7 +171,7 @@ function _getVidParams(attributes) { protocols = [], playerSize = [] } = attributes; - const sizes = utils.parseSizesInput(playerSize); + const sizes = parseSizesInput(playerSize); const [viw, vih] = sizes[0] && sizes[0].split('x'); let pr = ''; @@ -279,7 +277,7 @@ function buildRequests(validBidRequests, bidderRequest) { const uspConsent = bidderRequest && bidderRequest.uspConsent; const timeout = config.getConfig('bidderTimeout'); const topWindowUrl = bidderRequest && bidderRequest.refererInfo && bidderRequest.refererInfo.referer; - utils._each(validBidRequests, bidRequest => { + _each(validBidRequests, bidRequest => { const { bidId, mediaTypes = {}, @@ -299,9 +297,9 @@ function buildRequests(validBidRequests, bidderRequest) { for (const eid in eids) data[eid] = eids[eid]; // ADJS-1024 & ADSS-1297 - if (utils.deepAccess(ortb2Imp, 'ext.data.pbadslot')) { - gpid = utils.deepAccess(ortb2Imp, 'ext.data.pbadslot') - } else if (utils.deepAccess(ortb2Imp, 'ext.data.adserver.name')) { + if (deepAccess(ortb2Imp, 'ext.data.pbadslot')) { + gpid = deepAccess(ortb2Imp, 'ext.data.pbadslot') + } else if (deepAccess(ortb2Imp, 'ext.data.adserver.name')) { gpid = ortb2Imp.ext.data.adserver.adslot } @@ -435,7 +433,7 @@ function interpretResponse(serverResponse, bidRequest) { setTimeout(() => { !!invalidRequestIds[id] && delete invalidRequestIds[id]; }, delayTime); - utils.logWarn(`[GumGum] Please check the implementation for ${id}`); + logWarn(`[GumGum] Please check the implementation for ${id}`); } const defaultResponse = { @@ -483,14 +481,14 @@ function interpretResponse(serverResponse, bidRequest) { advertiserDomains: advertiserDomains || [], mediaType: type || mediaType }; - let sizes = utils.parseSizesInput(bidRequest.sizes); + let sizes = parseSizesInput(bidRequest.sizes); if (maxw && maxh) { sizes = [`${maxw}x${maxh}`]; } else if (product === 5 && includes(sizes, '1x1')) { sizes = ['1x1']; } else if (product === 2 && includes(sizes, '1x1')) { - sizes = responseWidth && responseHeight ? [`${responseWidth}x${responseHeight}`] : utils.parseSizesInput(bidRequest.sizes) + sizes = responseWidth && responseHeight ? [`${responseWidth}x${responseHeight}`] : parseSizesInput(bidRequest.sizes) } let [width, height] = sizes[0].split('x'); diff --git a/modules/h12mediaBidAdapter.js b/modules/h12mediaBidAdapter.js index 7b736780226..9a6244a9e82 100644 --- a/modules/h12mediaBidAdapter.js +++ b/modules/h12mediaBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { inIframe, logError, logMessage, deepAccess } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'h12media'; const DEFAULT_URL = 'https://bidder.h12-media.com/prebid/'; @@ -15,7 +15,7 @@ export const spec = { }, buildRequests: function(validBidRequests, bidderRequest) { - const isiframe = utils.inIframe(); + const isiframe = inIframe(); const screenSize = getClientDimensions(); const docSize = getDocumentDimensions(); @@ -24,7 +24,7 @@ export const spec = { const requestUrl = bidderParams.endpointdom || DEFAULT_URL; let pubsubid = bidderParams.pubsubid || ''; if (pubsubid && pubsubid.length > 32) { - utils.logError('Bidder param \'pubsubid\' should be not more than 32 chars.'); + logError('Bidder param \'pubsubid\' should be not more than 32 chars.'); pubsubid = ''; } const pubcontainerid = bidderParams.pubcontainerid; @@ -57,7 +57,7 @@ export const spec = { try { windowTop = window.top; } catch (e) { - utils.logMessage(e); + logMessage(e); windowTop = window; } @@ -66,11 +66,11 @@ export const spec = { url: requestUrl, options: {withCredentials: true}, data: { - gdpr: !!utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies', false), - gdpr_cs: utils.deepAccess(bidderRequest, 'gdprConsent.consentString', ''), - usp: !!utils.deepAccess(bidderRequest, 'uspConsent', false), - usp_cs: utils.deepAccess(bidderRequest, 'uspConsent', ''), - topLevelUrl: utils.deepAccess(bidderRequest, 'refererInfo.referer', ''), + gdpr: !!deepAccess(bidderRequest, 'gdprConsent.gdprApplies', false), + gdpr_cs: deepAccess(bidderRequest, 'gdprConsent.consentString', ''), + usp: !!deepAccess(bidderRequest, 'uspConsent', false), + usp_cs: deepAccess(bidderRequest, 'uspConsent', ''), + topLevelUrl: deepAccess(bidderRequest, 'refererInfo.referer', ''), refererUrl: windowTop.document.referrer, isiframe, version: '$prebid.version$', @@ -122,14 +122,14 @@ export const spec = { } return bidResponses; } catch (err) { - utils.logError(err); + logError(err); } }, getUserSyncs: function(syncOptions, serverResponses, gdprConsent, usPrivacy) { const syncs = []; - const uspApplies = !!utils.deepAccess(usPrivacy, 'uspConsent', false); - const uspString = utils.deepAccess(usPrivacy, 'uspConsent', ''); + const uspApplies = !!deepAccess(usPrivacy, 'uspConsent', false); + const uspString = deepAccess(usPrivacy, 'uspConsent', ''); gdprConsent = gdprConsent || { gdprApplies: false, consentString: '', }; diff --git a/modules/haloIdSystem.js b/modules/haloIdSystem.js index 3011569a17d..e961f75d31b 100644 --- a/modules/haloIdSystem.js +++ b/modules/haloIdSystem.js @@ -8,7 +8,7 @@ import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; import {submodule} from '../src/hook.js'; -import * as utils from '../src/utils.js'; +import { isFn, isStr, isPlainObject, logError } from '../src/utils.js'; const MODULE_NAME = 'haloId'; const AU_GVLID = 561; @@ -21,9 +21,9 @@ export const storage = getStorageManager(AU_GVLID, 'halo'); * @param {String} defaultVal */ function paramOrDefault(param, defaultVal, arg) { - if (utils.isFn(param)) { + if (isFn(param)) { return param(arg); - } else if (utils.isStr(param)) { + } else if (isStr(param)) { return param; } return defaultVal; @@ -44,7 +44,7 @@ export const haloIdSubmodule = { */ decode(value) { let haloId = storage.getDataFromLocalStorage('auHaloId'); - if (utils.isStr(haloId)) { + if (isStr(haloId)) { return {haloId: haloId}; } return (value && typeof value['haloId'] === 'string') ? { 'haloId': value['haloId'] } : undefined; @@ -56,7 +56,7 @@ export const haloIdSubmodule = { * @returns {IdResponse|undefined} */ getId(config) { - if (!utils.isPlainObject(config.params)) { + if (!isPlainObject(config.params)) { config.params = {}; } const url = paramOrDefault(config.params.url, @@ -65,7 +65,7 @@ export const haloIdSubmodule = { const resp = function (callback) { let haloId = storage.getDataFromLocalStorage('auHaloId'); - if (utils.isStr(haloId)) { + if (isStr(haloId)) { const responseObj = {haloId: haloId}; callback(responseObj); } else { @@ -76,13 +76,13 @@ export const haloIdSubmodule = { try { responseObj = JSON.parse(response); } catch (error) { - utils.logError(error); + logError(error); } } callback(responseObj); }, error: error => { - utils.logError(`${MODULE_NAME}: ID fetch encountered an error`, error); + logError(`${MODULE_NAME}: ID fetch encountered an error`, error); callback(); } }; diff --git a/modules/hybridBidAdapter.js b/modules/hybridBidAdapter.js index 15f8acd824f..4383e62c16e 100644 --- a/modules/hybridBidAdapter.js +++ b/modules/hybridBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js' +import { _map, logWarn, deepAccess, isArray } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js' import { auctionManager } from '../src/auctionManager.js' import { BANNER, VIDEO } from '../src/mediaTypes.js' @@ -21,7 +21,7 @@ const placementTypes = { }; function buildBidRequests(validBidRequests) { - return utils._map(validBidRequests, function(validBidRequest) { + return _map(validBidRequests, function(validBidRequest) { const params = validBidRequest.params; const bidRequest = { bidId: validBidRequest.bidId, @@ -63,7 +63,7 @@ const createRenderer = (bid) => { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; @@ -143,8 +143,8 @@ function hasVideoMandatoryParams(mediaTypes) { const isHasVideoContext = !!mediaTypes.video && (mediaTypes.video.context === 'instream' || mediaTypes.video.context === 'outstream'); const isPlayerSize = - !!utils.deepAccess(mediaTypes, 'video.playerSize') && - utils.isArray(utils.deepAccess(mediaTypes, 'video.playerSize')); + !!deepAccess(mediaTypes, 'video.playerSize') && + isArray(deepAccess(mediaTypes, 'video.playerSize')); return isHasVideoContext && isPlayerSize; } @@ -237,8 +237,8 @@ export const spec = { let bidRequests = JSON.parse(bidRequest.data).bidRequests; const serverBody = serverResponse.body; - if (serverBody && serverBody.bids && utils.isArray(serverBody.bids)) { - return utils._map(serverBody.bids, function(bid) { + if (serverBody && serverBody.bids && isArray(serverBody.bids)) { + return _map(serverBody.bids, function(bid) { let rawBid = find(bidRequests, function (item) { return item.bidId === bid.bidId; }); diff --git a/modules/iasRtdProvider.js b/modules/iasRtdProvider.js index a1ff57971ba..25ca39c23d6 100644 --- a/modules/iasRtdProvider.js +++ b/modules/iasRtdProvider.js @@ -1,6 +1,6 @@ +import { isArray, getAdUnitSizes, getKeys, logError } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { getGlobal } from '../src/prebidGlobal.js'; -import * as utils from '../src/utils.js'; import { ajaxBuilder } from '../src/ajax.js'; /** @type {string} */ @@ -21,7 +21,7 @@ export function init(config, userConsent) { function stringifySlotSizes(sizes) { let result = ''; - if (utils.isArray(sizes)) { + if (isArray(sizes)) { result = sizes.reduce((acc, size) => { acc.push(size.join('.')); return acc; @@ -32,12 +32,12 @@ function stringifySlotSizes(sizes) { } function stringifySlot(bidRequest, adUnitPath) { - const sizes = utils.getAdUnitSizes(bidRequest); + const sizes = getAdUnitSizes(bidRequest); const id = bidRequest.code; const ss = stringifySlotSizes(sizes); const p = bidRequest.code; const slot = { id, ss, p }; - const keyValues = utils.getKeys(slot).map(function (key) { + const keyValues = getKeys(slot).map(function (key) { return [key, slot[key]].join(':'); }); return '{' + keyValues.join(',') + '}'; @@ -62,7 +62,7 @@ function getPageLevelKeywords(response) { } function shallowMerge(dest, src) { - utils.getKeys(src).reduce((dest, srcKey) => { + getKeys(src).reduce((dest, srcKey) => { dest[srcKey] = src[srcKey]; return dest; }, dest); @@ -114,7 +114,7 @@ function getBidRequestData(reqBidsConfigObj, callback, config) { callback(); }, error: function () { - utils.logError('failed to retrieve targeting information'); + logError('failed to retrieve targeting information'); callback(); } }); @@ -128,7 +128,7 @@ function getTargetingData(adUnits, config, userConsent) { targeting[adUnit] = bidResponses; }); } catch (err) { - utils.logError('error', err); + logError('error', err); } return targeting; } diff --git a/modules/id5IdSystem.js b/modules/id5IdSystem.js index d2d64f52738..43d26224164 100644 --- a/modules/id5IdSystem.js +++ b/modules/id5IdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { deepAccess, logInfo, deepSetValue, logError, isEmpty, isEmptyStr, logWarn } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; import { getRefererInfo } from '../src/refererDetection.js'; @@ -67,25 +67,25 @@ export const id5IdSubmodule = { } }; - const abTestingResult = utils.deepAccess(value, 'ab_testing.result'); + const abTestingResult = deepAccess(value, 'ab_testing.result'); switch (abTestingResult) { case 'control': // A/B Testing is enabled and user is in the Control Group - utils.logInfo(LOG_PREFIX + 'A/B Testing - user is in the Control Group: ID5 ID is NOT exposed'); - utils.deepSetValue(responseObj, 'id5id.ext.abTestingControlGroup', true); + logInfo(LOG_PREFIX + 'A/B Testing - user is in the Control Group: ID5 ID is NOT exposed'); + deepSetValue(responseObj, 'id5id.ext.abTestingControlGroup', true); break; case 'error': // A/B Testing is enabled, but configured improperly, so skip A/B testing - utils.logError(LOG_PREFIX + 'A/B Testing ERROR! controlGroupPct must be a number >= 0 and <= 1'); + logError(LOG_PREFIX + 'A/B Testing ERROR! controlGroupPct must be a number >= 0 and <= 1'); break; case 'normal': // A/B Testing is enabled but user is not in the Control Group, so ID5 ID is shared - utils.logInfo(LOG_PREFIX + 'A/B Testing - user is NOT in the Control Group'); - utils.deepSetValue(responseObj, 'id5id.ext.abTestingControlGroup', false); + logInfo(LOG_PREFIX + 'A/B Testing - user is NOT in the Control Group'); + deepSetValue(responseObj, 'id5id.ext.abTestingControlGroup', false); break; } - utils.logInfo(LOG_PREFIX + 'Decoded ID', responseObj); + logInfo(LOG_PREFIX + 'Decoded ID', responseObj); return responseObj; }, @@ -120,19 +120,19 @@ export const id5IdSubmodule = { }; // pass in optional data, but only if populated - if (hasGdpr && typeof consentData.consentString !== 'undefined' && !utils.isEmpty(consentData.consentString) && !utils.isEmptyStr(consentData.consentString)) { + if (hasGdpr && typeof consentData.consentString !== 'undefined' && !isEmpty(consentData.consentString) && !isEmptyStr(consentData.consentString)) { data.gdpr_consent = consentData.consentString; } - if (typeof usp !== 'undefined' && !utils.isEmpty(usp) && !utils.isEmptyStr(usp)) { + if (typeof usp !== 'undefined' && !isEmpty(usp) && !isEmptyStr(usp)) { data.us_privacy = usp; } - if (typeof signature !== 'undefined' && !utils.isEmptyStr(signature)) { + if (typeof signature !== 'undefined' && !isEmptyStr(signature)) { data.s = signature; } - if (typeof config.params.pd !== 'undefined' && !utils.isEmptyStr(config.params.pd)) { + if (typeof config.params.pd !== 'undefined' && !isEmptyStr(config.params.pd)) { data.pd = config.params.pd; } - if (typeof config.params.provider !== 'undefined' && !utils.isEmptyStr(config.params.provider)) { + if (typeof config.params.provider !== 'undefined' && !isEmptyStr(config.params.provider)) { data.provider = config.params.provider; } @@ -151,7 +151,7 @@ export const id5IdSubmodule = { if (response) { try { responseObj = JSON.parse(response); - utils.logInfo(LOG_PREFIX + 'response received from the server', responseObj); + logInfo(LOG_PREFIX + 'response received from the server', responseObj); resetNb(config.params.partner); @@ -165,17 +165,17 @@ export const id5IdSubmodule = { removeLegacyCookies(config.params.partner); } } catch (error) { - utils.logError(LOG_PREFIX + error); + logError(LOG_PREFIX + error); } } callback(responseObj); }, error: error => { - utils.logError(LOG_PREFIX + 'getId fetch encountered an error', error); + logError(LOG_PREFIX + 'getId fetch encountered an error', error); callback(); } }; - utils.logInfo(LOG_PREFIX + 'requesting an ID from the server', data); + logInfo(LOG_PREFIX + 'requesting an ID from the server', data); ajax(url, callbacks, JSON.stringify(data), { method: 'POST', withCredentials: true }); }; return { callback: resp }; @@ -198,29 +198,29 @@ export const id5IdSubmodule = { const partnerId = (config && config.params && config.params.partner) || 0; incrementNb(partnerId); - utils.logInfo(LOG_PREFIX + 'using cached ID', cacheIdObj); + logInfo(LOG_PREFIX + 'using cached ID', cacheIdObj); return cacheIdObj; } }; function hasRequiredConfig(config) { if (!config || !config.params || !config.params.partner || typeof config.params.partner !== 'number') { - utils.logError(LOG_PREFIX + 'partner required to be defined as a number'); + logError(LOG_PREFIX + 'partner required to be defined as a number'); return false; } if (!config.storage || !config.storage.type || !config.storage.name) { - utils.logError(LOG_PREFIX + 'storage required to be set'); + logError(LOG_PREFIX + 'storage required to be set'); return false; } // in a future release, we may return false if storage type or name are not set as required if (config.storage.type !== LOCAL_STORAGE) { - utils.logWarn(LOG_PREFIX + `storage type recommended to be '${LOCAL_STORAGE}'. In a future release this may become a strict requirement`); + logWarn(LOG_PREFIX + `storage type recommended to be '${LOCAL_STORAGE}'. In a future release this may become a strict requirement`); } // in a future release, we may return false if storage type or name are not set as required if (config.storage.name !== ID5_STORAGE_NAME) { - utils.logWarn(LOG_PREFIX + `storage name recommended to be '${ID5_STORAGE_NAME}'. In a future release this may become a strict requirement`); + logWarn(LOG_PREFIX + `storage name recommended to be '${ID5_STORAGE_NAME}'. In a future release this may become a strict requirement`); } return true; @@ -265,7 +265,7 @@ function getLegacyCookieSignature() { * @param {integer} partnerId */ function removeLegacyCookies(partnerId) { - utils.logInfo(LOG_PREFIX + 'removing legacy cookies'); + logInfo(LOG_PREFIX + 'removing legacy cookies'); LEGACY_COOKIE_NAMES.forEach(function(cookie) { storage.setCookie(`${cookie}`, ' ', expDaysStr(-1)); storage.setCookie(`${cookie}_nb`, ' ', expDaysStr(-1)); @@ -313,7 +313,7 @@ export function storeInLocalStorage(key, value, expDays) { * @returns {Object} an object which always contains at least the property "enabled" */ function getAbTestingConfig(config) { - return utils.deepAccess(config, 'params.abTesting', { enabled: false }); + return deepAccess(config, 'params.abTesting', { enabled: false }); } submodule('userId', id5IdSubmodule); diff --git a/modules/idImportLibrary.js b/modules/idImportLibrary.js index 2a3a86cf270..e266f10cc4e 100644 --- a/modules/idImportLibrary.js +++ b/modules/idImportLibrary.js @@ -1,7 +1,7 @@ +import { logInfo, logError } from '../src/utils.js'; import {getGlobal} from '../src/prebidGlobal.js'; import {ajax} from '../src/ajax.js'; import {config} from '../src/config.js'; -import * as utils from '../src/utils.js'; import MD5 from 'crypto-js/md5.js'; let email; @@ -18,18 +18,18 @@ const OBSERVER_CONFIG = { characterData: true, characterDataOldValue: false }; -const logInfo = createLogInfo(LOG_PRE_FIX); -const logError = createLogError(LOG_PRE_FIX); +const _logInfo = createLogInfo(LOG_PRE_FIX); +const _logError = createLogError(LOG_PRE_FIX); function createLogInfo(prefix) { return function (...strings) { - utils.logInfo(prefix + ' ', ...strings); + logInfo(prefix + ' ', ...strings); } } function createLogError(prefix) { return function (...strings) { - utils.logError(prefix + ' ', ...strings); + logError(prefix + ' ', ...strings); } } @@ -38,39 +38,39 @@ function getEmail(value) { if (!matched) { return null; } - logInfo('Email found: ' + matched[0]); + _logInfo('Email found: ' + matched[0]); return matched[0]; } function bodyAction(mutations, observer) { - logInfo('BODY observer on debounce called'); + _logInfo('BODY observer on debounce called'); // If the email is found in the input element, disconnect the observer if (email) { observer.disconnect(); - logInfo('Email is found, body observer disconnected'); + _logInfo('Email is found, body observer disconnected'); return; } const body = document.body.innerHTML; email = getEmail(body); if (email !== null) { - logInfo(`Email obtained from the body ${email}`); + _logInfo(`Email obtained from the body ${email}`); observer.disconnect(); - logInfo('Post data on email found in body'); + _logInfo('Post data on email found in body'); postData(); } } function targetAction(mutations, observer) { - logInfo('Target observer called'); + _logInfo('Target observer called'); for (const mutation of mutations) { for (const node of mutation.addedNodes) { email = node.textContent; if (email) { - logInfo('Email obtained from the target ' + email); + _logInfo('Email obtained from the target ' + email); observer.disconnect(); - logInfo('Post data on email found in target'); + _logInfo('Post data on email found in target'); postData(); return; } @@ -79,18 +79,18 @@ function targetAction(mutations, observer) { } function addInputElementsElementListner(conf) { - logInfo('Adding input element listeners'); + _logInfo('Adding input element listeners'); const inputs = document.querySelectorAll('input[type=text], input[type=email]'); for (var i = 0; i < inputs.length; i++) { - logInfo(`Original Value in Input = ${inputs[i].value}`); + _logInfo(`Original Value in Input = ${inputs[i].value}`); inputs[i].addEventListener('change', event => processInputChange(event)); inputs[i].addEventListener('blur', event => processInputChange(event)); } } function removeInputElementsElementListner() { - logInfo('Removing input element listeners'); + _logInfo('Removing input element listeners'); const inputs = document.querySelectorAll('input[type=text], input[type=email]'); for (var i = 0; i < inputs.length; i++) { @@ -101,10 +101,10 @@ function removeInputElementsElementListner() { function processInputChange(event) { const value = event.target.value; - logInfo(`Modified Value of input ${event.target.value}`); + _logInfo(`Modified Value of input ${event.target.value}`); email = getEmail(value); if (email !== null) { - logInfo('Email found in input ' + email); + _logInfo('Email found in input ' + email); postData(); removeInputElementsElementListner(); } @@ -124,7 +124,7 @@ function debounce(func, wait, immediate) { if (callNow) { func.apply(context, args); } else { - logInfo('Debounce wait time ' + wait); + _logInfo('Debounce wait time ' + wait); timeout = setTimeout(later, wait); } }; @@ -138,11 +138,11 @@ function handleTargetElement() { email = targetElement.innerText; if (!email) { - logInfo('Finding the email with observer'); + _logInfo('Finding the email with observer'); targetObserver.observe(targetElement, OBSERVER_CONFIG); } else { - logInfo('Target found with target ' + email); - logInfo('Post data on email found in target with target'); + _logInfo('Target found with target ' + email); + _logInfo('Post data on email found in target with target'); postData(); } } @@ -150,15 +150,15 @@ function handleTargetElement() { function handleBodyElements() { if (doesInputElementsHaveEmail()) { - logInfo('Email found in input elements ' + email); - logInfo('Post data on email found in target without'); + _logInfo('Email found in input elements ' + email); + _logInfo('Post data on email found in target without'); postData(); return; } email = getEmail(document.body.innerHTML); if (email !== null) { - logInfo('Email found in body ' + email); - logInfo('Post data on email found in the body without observer'); + _logInfo('Email found in body ' + email); + _logInfo('Post data on email found in the body without observer'); postData(); return; } @@ -185,10 +185,10 @@ function doesInputElementsHaveEmail() { function syncCallback() { return { success: function () { - logInfo('Data synced successfully.'); + _logInfo('Data synced successfully.'); }, error: function () { - logInfo('Data sync failed.'); + _logInfo('Data sync failed.'); } } } @@ -197,15 +197,15 @@ function postData() { (getGlobal()).refreshUserIds(); const userIds = (getGlobal()).getUserIds(); if (Object.keys(userIds).length === 0) { - logInfo('No user ids'); + _logInfo('No user ids'); return; } - logInfo('Users' + userIds); + _logInfo('Users' + userIds); const syncPayload = {}; syncPayload.hid = MD5(email).toString(); syncPayload.uids = userIds; const payloadString = JSON.stringify(syncPayload); - logInfo(payloadString); + _logInfo(payloadString); ajax(conf.url, syncCallback(), payloadString, {method: 'POST', withCredentials: true}); } @@ -221,20 +221,20 @@ function associateIds() { export function setConfig(config) { if (!config) { - logError('Required confirguration not provided'); + _logError('Required confirguration not provided'); return; } if (!config.url) { - logError('The required url is not configured'); + _logError('The required url is not configured'); return; } if (typeof config.debounce !== 'number') { config.debounce = CONF_DEFAULT_OBSERVER_DEBOUNCE_MS; - logInfo('Set default observer debounce to ' + CONF_DEFAULT_OBSERVER_DEBOUNCE_MS); + _logInfo('Set default observer debounce to ' + CONF_DEFAULT_OBSERVER_DEBOUNCE_MS); } if (typeof config.fullscan !== 'boolean') { config.fullscan = CONF_DEFAULT_FULL_BODY_SCAN; - logInfo('Set default fullscan ' + CONF_DEFAULT_FULL_BODY_SCAN); + _logInfo('Set default fullscan ' + CONF_DEFAULT_FULL_BODY_SCAN); } conf = config; associateIds(); diff --git a/modules/idxIdSystem.js b/modules/idxIdSystem.js index 00e8a8bc5e5..908edad4c04 100644 --- a/modules/idxIdSystem.js +++ b/modules/idxIdSystem.js @@ -4,7 +4,7 @@ * @module modules/idxIdSystem * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { isStr, isPlainObject, logError } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -34,7 +34,7 @@ export const idxIdSubmodule = { * @return { Object | string | undefined } */ decode(value) { - const idxVal = value ? utils.isStr(value) ? value : utils.isPlainObject(value) ? value.id : undefined : undefined; + const idxVal = value ? isStr(value) ? value : isPlainObject(value) ? value.id : undefined : undefined; return idxVal ? { 'idx': idxVal } : undefined; @@ -52,7 +52,7 @@ export const idxIdSubmodule = { const idxObj = JSON.parse(idxString); return idxObj && idxObj.idx ? { id: idxObj.idx } : undefined; } catch (error) { - utils.logError(error); + logError(error); } } return undefined; diff --git a/modules/impactifyBidAdapter.js b/modules/impactifyBidAdapter.js index 5b0b1dff048..b204e81f22c 100644 --- a/modules/impactifyBidAdapter.js +++ b/modules/impactifyBidAdapter.js @@ -1,5 +1,5 @@ +import { deepAccess, deepSetValue, generateUUID } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import { config } from '../src/config.js'; import {ajax} from '../src/ajax.js'; import { createEidsArray } from './userId/eids.js'; @@ -43,14 +43,14 @@ const createOpenRtbRequest = (validBidRequests, bidderRequest) => { } // Set Schain in request - let schain = utils.deepAccess(validBidRequests, '0.schain'); + let schain = deepAccess(validBidRequests, '0.schain'); if (schain) request.source.ext = { schain: schain }; // Set eids - let bidUserId = utils.deepAccess(validBidRequests, '0.userId'); + let bidUserId = deepAccess(validBidRequests, '0.userId'); let eids = createEidsArray(bidUserId); if (eids.length) { - utils.deepSetValue(request, 'user.ext.eids', eids); + deepSetValue(request, 'user.ext.eids', eids); } // Set device/user/site @@ -71,23 +71,23 @@ const createOpenRtbRequest = (validBidRequests, bidderRequest) => { let gdprApplies = 0; if (bidderRequest.gdprConsent) { if (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') gdprApplies = bidderRequest.gdprConsent.gdprApplies ? 1 : 0; - utils.deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString); } - utils.deepSetValue(request, 'regs.ext.gdpr', gdprApplies); + deepSetValue(request, 'regs.ext.gdpr', gdprApplies); if (bidderRequest.uspConsent) { - utils.deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); this.syncStore.uspConsent = bidderRequest.uspConsent; } - if (GETCONFIG('coppa') == true) utils.deepSetValue(request, 'regs.coppa', 1); + if (GETCONFIG('coppa') == true) deepSetValue(request, 'regs.coppa', 1); if (bidderRequest.uspConsent) { - utils.deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); + deepSetValue(request, 'regs.ext.us_privacy', bidderRequest.uspConsent); } // Set buyer uid - utils.deepSetValue(request, 'user.buyeruid', utils.generateUUID()); + deepSetValue(request, 'user.buyeruid', generateUUID()); // Create imps with bids validBidRequests.forEach((bid) => { diff --git a/modules/improvedigitalBidAdapter.js b/modules/improvedigitalBidAdapter.js index e73df68b625..688a8815e93 100644 --- a/modules/improvedigitalBidAdapter.js +++ b/modules/improvedigitalBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { deepSetValue, logError, _each, getBidRequest, isNumber, isArray, deepAccess, isFn, isPlainObject, logWarn, getBidIdParameter, getUniqueIdentifierStr, isEmpty, isInteger } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; @@ -62,7 +62,7 @@ export const spec = { if (bidRequests[0].userId) { const eids = createEidsArray(bidRequests[0].userId); if (eids.length) { - utils.deepSetValue(requestParameters, 'user.ext.eids', eids); + deepSetValue(requestParameters, 'user.ext.eids', eids); } } @@ -72,7 +72,7 @@ export const spec = { ); if (requestObj.errors && requestObj.errors.length > 0) { - utils.logError('ID WARNING 0x01'); + logError('ID WARNING 0x01'); } requestObj.requests.forEach(request => request.bidderRequest = bidderRequest); return requestObj.requests; @@ -86,13 +86,13 @@ export const spec = { */ interpretResponse: function (serverResponse, {bidderRequest}) { const bids = []; - utils._each(serverResponse.body.bid, function (bidObject) { + _each(serverResponse.body.bid, function (bidObject) { if (!bidObject.price || bidObject.price === null || bidObject.hasOwnProperty('errorCode') || (!bidObject.adm && !bidObject.native)) { return; } - const bidRequest = utils.getBidRequest(bidObject.id, [bidderRequest]); + const bidRequest = getBidRequest(bidObject.id, [bidderRequest]); const bid = {}; if (bidObject.native) { @@ -132,7 +132,7 @@ export const spec = { // Deal ID. Composite ads can have multiple line items and the ID of the first // dealID line item will be used. - if (utils.isNumber(bidObject.lid) && bidObject.buying_type && bidObject.buying_type !== 'rtb') { + if (isNumber(bidObject.lid) && bidObject.buying_type && bidObject.buying_type !== 'rtb') { bid.dealId = bidObject.lid; } else if (Array.isArray(bidObject.lid) && Array.isArray(bidObject.buying_type) && @@ -181,7 +181,7 @@ export const spec = { const syncs = []; serverResponses.forEach(response => { response.body.bid.forEach(bidObject => { - if (utils.isArray(bidObject.sync)) { + if (isArray(bidObject.sync)) { bidObject.sync.forEach(syncElement => { if (syncs.indexOf(syncElement) === -1) { syncs.push(syncElement); @@ -197,15 +197,15 @@ export const spec = { }; function isInstreamVideo(bid) { - const mediaTypes = Object.keys(utils.deepAccess(bid, 'mediaTypes', {})); - const videoMediaType = utils.deepAccess(bid, 'mediaTypes.video'); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const mediaTypes = Object.keys(deepAccess(bid, 'mediaTypes', {})); + const videoMediaType = deepAccess(bid, 'mediaTypes.video'); + const context = deepAccess(bid, 'mediaTypes.video.context'); return bid.mediaType === 'video' || (mediaTypes.length === 1 && videoMediaType && context !== 'outstream'); } function isOutstreamVideo(bid) { - const videoMediaType = utils.deepAccess(bid, 'mediaTypes.video'); - const context = utils.deepAccess(bid, 'mediaTypes.video.context'); + const videoMediaType = deepAccess(bid, 'mediaTypes.video'); + const context = deepAccess(bid, 'mediaTypes.video.context'); return videoMediaType && context === 'outstream'; } @@ -225,7 +225,7 @@ function getVideoTargetingParams(bid) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return null; } const floor = bid.getFloor({ @@ -233,7 +233,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'USD') { return floor.floor; } return null; @@ -259,31 +259,31 @@ function createRenderer(bidRequest) { id: bidRequest.adUnitCode, url: RENDERER_URL, loaded: false, - config: utils.deepAccess(bidRequest, 'renderer.options'), + config: deepAccess(bidRequest, 'renderer.options'), adUnitCode: bidRequest.adUnitCode }); try { renderer.setRender(outstreamRender); } catch (err) { - utils.logWarn('Prebid Error calling setRender on renderer', err); + logWarn('Prebid Error calling setRender on renderer', err); } return renderer; } function getNormalizedBidRequest(bid) { - let adUnitId = utils.getBidIdParameter('adUnitCode', bid) || null; - let placementId = utils.getBidIdParameter('placementId', bid.params) || null; + let adUnitId = getBidIdParameter('adUnitCode', bid) || null; + let placementId = getBidIdParameter('placementId', bid.params) || null; let publisherId = null; let placementKey = null; if (placementId === null) { - publisherId = utils.getBidIdParameter('publisherId', bid.params) || null; - placementKey = utils.getBidIdParameter('placementKey', bid.params) || null; + publisherId = getBidIdParameter('publisherId', bid.params) || null; + placementKey = getBidIdParameter('placementKey', bid.params) || null; } - const keyValues = utils.getBidIdParameter('keyValues', bid.params) || null; - const singleSizeFilter = utils.getBidIdParameter('size', bid.params) || null; - const bidId = utils.getBidIdParameter('bidId', bid); - const transactionId = utils.getBidIdParameter('transactionId', bid); + const keyValues = getBidIdParameter('keyValues', bid.params) || null; + const singleSizeFilter = getBidIdParameter('size', bid.params) || null; + const bidId = getBidIdParameter('bidId', bid); + const transactionId = getBidIdParameter('transactionId', bid); const currency = config.getConfig('currency.adServerCurrency'); let normalizedBidRequest = {}; @@ -332,8 +332,8 @@ function getNormalizedBidRequest(bid) { let bidFloor = getBidFloor(bid); let bidFloorCur = null; if (!bidFloor) { - bidFloor = utils.getBidIdParameter('bidFloor', bid.params); - bidFloorCur = utils.getBidIdParameter('bidFloorCur', bid.params); + bidFloor = getBidIdParameter('bidFloor', bid.params); + bidFloorCur = getBidIdParameter('bidFloorCur', bid.params); } if (bidFloor) { normalizedBidRequest.bidFloor = bidFloor; @@ -344,7 +344,7 @@ function getNormalizedBidRequest(bid) { function getNormalizedNativeAd(rawNative) { const native = {}; - if (!rawNative || !utils.isArray(rawNative.assets)) { + if (!rawNative || !isArray(rawNative.assets)) { return null; } // Assets @@ -475,7 +475,7 @@ export function ImproveDigitalAdServerJSClient(endPoint) { let impressionObjects = []; let impressionObject; - if (utils.isArray(requestObject)) { + if (isArray(requestObject)) { for (let counter = 0; counter < requestObject.length; counter++) { impressionObject = this.createImpressionObject(requestObject[counter]); impressionObjects.push(impressionObject); @@ -576,7 +576,7 @@ export function ImproveDigitalAdServerJSClient(endPoint) { if (requestParameters.requestId) { impressionBidRequestObject.id = requestParameters.requestId; } else { - impressionBidRequestObject.id = utils.getUniqueIdentifierStr(); + impressionBidRequestObject.id = getUniqueIdentifierStr(); } if (requestParameters.domain) { impressionBidRequestObject.domain = requestParameters.domain; @@ -625,7 +625,7 @@ export function ImproveDigitalAdServerJSClient(endPoint) { if (placementObject.id) { impressionObject.id = placementObject.id; } else { - impressionObject.id = utils.getUniqueIdentifierStr(); + impressionObject.id = getUniqueIdentifierStr(); } if (placementObject.adTypes) { impressionObject.ad_types = placementObject.adTypes; @@ -654,18 +654,18 @@ export function ImproveDigitalAdServerJSClient(endPoint) { if (placementObject.transactionId) { impressionObject.tid = placementObject.transactionId; } - if (!utils.isEmpty(placementObject.video)) { + if (!isEmpty(placementObject.video)) { const video = Object.assign({}, placementObject.video); // skip must be 0 or 1 if (video.skip !== 1) { delete video.skipmin; delete video.skipafter; if (video.skip !== 0) { - utils.logWarn(`video.skip: invalid value '${video.skip}'. Expected 0 or 1`); + logWarn(`video.skip: invalid value '${video.skip}'. Expected 0 or 1`); delete video.skip; } } - if (!utils.isEmpty(video)) { + if (!isEmpty(video)) { impressionObject.video = video; } } @@ -687,11 +687,11 @@ export function ImproveDigitalAdServerJSClient(endPoint) { // Set of desired creative sizes // Input Format: array of pairs, i.e. [[300, 250], [250, 250]] - if (placementObject.format && utils.isArray(placementObject.format)) { + if (placementObject.format && isArray(placementObject.format)) { const format = placementObject.format .filter(sizePair => sizePair.length === 2 && - utils.isInteger(sizePair[0]) && - utils.isInteger(sizePair[1]) && + isInteger(sizePair[0]) && + isInteger(sizePair[1]) && sizePair[0] >= 0 && sizePair[1] >= 0) .map(sizePair => { diff --git a/modules/imuIdSystem.js b/modules/imuIdSystem.js index da03c63fc8a..72e81d243a3 100644 --- a/modules/imuIdSystem.js +++ b/modules/imuIdSystem.js @@ -5,7 +5,7 @@ * @requires module:modules/userId */ -import * as utils from '../src/utils.js' +import { timestamp, logError } from '../src/utils.js'; import { ajax } from '../src/ajax.js' import { submodule } from '../src/hook.js'; import { getStorageManager } from '../src/storageManager.js'; @@ -20,7 +20,7 @@ const cookiesMaxAge = 97200000000; // 37 months ((365 * 3 + 30) * 24 * 60 * 60 * export function setImDataInLocalStorage(value) { storage.setDataInLocalStorage(storageKey, value); - storage.setDataInLocalStorage(`${storageKey}_mt`, new Date(utils.timestamp()).toUTCString()); + storage.setDataInLocalStorage(`${storageKey}_mt`, new Date(timestamp()).toUTCString()); } export function removeImDataFromLocalStorage() { @@ -32,7 +32,7 @@ function setImDataInCookie(value) { storage.setCookie( cookieKey, value, - new Date(utils.timestamp() + cookiesMaxAge).toUTCString(), + new Date(timestamp() + cookiesMaxAge).toUTCString(), 'none' ); } @@ -73,7 +73,7 @@ export function getApiCallback(callback) { responseObj = JSON.parse(response); apiSuccessProcess(responseObj); } catch (error) { - utils.logError('User ID - imuid submodule: ' + error); + logError('User ID - imuid submodule: ' + error); } } if (callback && responseObj.uid) { @@ -81,7 +81,7 @@ export function getApiCallback(callback) { } }, error: error => { - utils.logError('User ID - imuid submodule was unable to get data from api: ' + error); + logError('User ID - imuid submodule was unable to get data from api: ' + error); if (callback) { callback(); } @@ -128,7 +128,7 @@ export const imuIdSubmodule = { getId(config) { const configParams = (config && config.params) || {}; if (!configParams || typeof configParams.cid !== 'number') { - utils.logError('User ID - imuid submodule requires a valid cid to be defined'); + logError('User ID - imuid submodule requires a valid cid to be defined'); return undefined; } let apiUrl = getApiUrl(configParams.cid, configParams.url); diff --git a/modules/inmarBidAdapter.js b/modules/inmarBidAdapter.js index e1edd935587..0e056551b35 100755 --- a/modules/inmarBidAdapter.js +++ b/modules/inmarBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logError } from '../src/utils.js'; import { config } from '../src/config.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; @@ -83,7 +83,7 @@ export const spec = { bidResponses.push(bidResponse); } } catch (error) { - utils.logError('Error while parsing inmar response', error); + logError('Error while parsing inmar response', error); } return bidResponses; }, diff --git a/modules/innityBidAdapter.js b/modules/innityBidAdapter.js index ab7ee07db4a..0a2f701ef64 100644 --- a/modules/innityBidAdapter.js +++ b/modules/innityBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { parseSizesInput, timestamp } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'innity'; @@ -11,13 +11,13 @@ export const spec = { }, buildRequests: function(validBidRequests, bidderRequest) { return validBidRequests.map(bidRequest => { - let parseSized = utils.parseSizesInput(bidRequest.sizes); + let parseSized = parseSizesInput(bidRequest.sizes); let arrSize = parseSized[0].split('x'); return { method: 'GET', url: ENDPOINT, data: { - cb: utils.timestamp(), + cb: timestamp(), ver: 2, hb: 1, output: 'js', diff --git a/modules/inskinBidAdapter.js b/modules/inskinBidAdapter.js index 8f2e35a41e0..b6d23bb7207 100644 --- a/modules/inskinBidAdapter.js +++ b/modules/inskinBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { createTrackPixelHtml } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; const BIDDER_CODE = 'inskin'; @@ -289,7 +289,7 @@ function getSize(sizes) { } function retrieveAd(bidId, decision) { - return ""'; +describe('slimcutBidAdapter', function() { + const adapter = newBidder(spec); + describe('inherited functions', function() { + it('exists and is a function', function() { + expect(adapter.callBids).to.exist.and.to.be.a('function'); + }); + }); + describe('isBidRequestValid', function() { + let bid = { + 'bidder': 'slimcut', + 'params': { + 'placementId': 83 + }, + 'adUnitCode': 'adunit-code', + 'sizes': [ + [300, 250], + [300, 600] + ], + 'bidId': '3c871ffa8ef14c', + 'bidderRequestId': 'b41642f1aee381', + 'auctionId': '4e156668c977d7' + }; + it('should return true when required params found', function() { + expect(spec.isBidRequestValid(bid)).to.equal(true); + }); + it('should return false when placementId is not valid (letters)', function() { + let bid = Object.assign({}, bid); + delete bid.params; + bid.params = { + 'placementId': 'ABCD' + }; + expect(spec.isBidRequestValid(bid)).to.equal(false); + }); + it('should return false when placementId < 0', function() { + let bid = Object.assign({}, bid); + delete bid.params; + bid.params = { + 'placementId': -1 + }; + expect(spec.isBidRequestValid(bid)).to.equal(false); + }); + it('should return false when required params are not passed', function() { + let bid = Object.assign({}, bid); + delete bid.params; + bid.params = {}; + expect(spec.isBidRequestValid(bid)).to.equal(false); + }); + }); + describe('buildRequests', function() { + let bidRequests = [{ + 'bidder': 'teads', + 'params': { + 'placementId': 10433394 + }, + 'adUnitCode': 'adunit-code', + 'sizes': [ + [300, 250], + [300, 600] + ], + 'bidId': '3c871ffa8ef14c', + 'bidderRequestId': 'b41642f1aee381', + 'auctionId': '4e156668c977d7', + 'deviceWidth': 1680 + }]; + let bidderResquestDefault = { + 'auctionId': '4e156668c977d7', + 'bidderRequestId': 'b41642f1aee381', + 'timeout': 3000 + }; + it('sends bid request to ENDPOINT via POST', function() { + const request = spec.buildRequests(bidRequests, bidderResquestDefault); + expect(request.url).to.equal(ENDPOINT); + expect(request.method).to.equal('POST'); + }); + it('should send GDPR to endpoint', function() { + let consentString = 'JRJ8RKfDeBNsERRDCSAAZ+A=='; + let bidderRequest = { + 'auctionId': '4e156668c977d7', + 'bidderRequestId': 'b41642f1aee381', + 'timeout': 3000, + 'gdprConsent': { + 'consentString': consentString, + 'gdprApplies': true, + 'vendorData': { + 'hasGlobalConsent': false + } + } + }; + const request = spec.buildRequests(bidRequests, bidderRequest); + const payload = JSON.parse(request.data); + expect(payload.gdpr_iab).to.exist; + expect(payload.gdpr_iab.consent).to.equal(consentString); + }); + it('should add referer info to payload', function() { + const bidRequest = Object.assign({}, bidRequests[0]) + const bidderRequest = { + refererInfo: { + referer: 'https://example.com/page.html', + reachedTop: true, + numIframes: 2 + } + } + const request = spec.buildRequests([bidRequest], bidderRequest); + const payload = JSON.parse(request.data); + expect(payload.referrer).to.exist; + expect(payload.referrer).to.deep.equal('https://example.com/page.html') + }); + }); + describe('getUserSyncs', () => { + let bids = { + 'body': { + 'responses': [{ + 'ad': AD_SCRIPT, + 'cpm': 0.5, + 'currency': 'USD', + 'height': 250, + 'netRevenue': true, + 'requestId': '3ede2a3fa0db94', + 'ttl': 360, + 'width': 300, + 'creativeId': 'er2ee', + 'transactionId': 'deadb33f', + 'winUrl': 'https://sb.freeskreen.com/win' + }] + } + }; + it('should get the correct number of sync urls', () => { + let urls = spec.getUserSyncs({ + iframeEnabled: true + }, bids); + expect(urls.length).to.equal(1); + expect(urls[0].url).to.equal('https://sb.freeskreen.com/async_usersync.html'); + }); + it('should return no url if not iframe enabled', () => { + let urls = spec.getUserSyncs({ + iframeEnabled: false + }, bids); + expect(urls.length).to.equal(0); + }); + }); + describe('interpretResponse', function() { + let bids = { + 'body': { + 'responses': [{ + 'ad': AD_SCRIPT, + 'cpm': 0.5, + 'currency': 'USD', + 'height': 250, + 'netRevenue': true, + 'requestId': '3ede2a3fa0db94', + 'ttl': 360, + 'width': 300, + 'creativeId': 'er2ee', + 'transactionId': 'deadb33f', + 'winUrl': 'https://sb.freeskreen.com/win' + }] + } + }; + it('should get correct bid response', function() { + let expectedResponse = [{ + 'cpm': 0.5, + 'width': 300, + 'height': 250, + 'currency': 'USD', + 'netRevenue': true, + 'ttl': 360, + 'ad': AD_SCRIPT, + 'requestId': '3ede2a3fa0db94', + 'creativeId': 'er2ee', + 'transactionId': 'deadb33f', + 'winUrl': 'https://sb.freeskreen.com/win', + 'meta': { + 'advertiserDomains': [] + } + }]; + let result = spec.interpretResponse(bids); + expect(Object.keys(result[0])).to.deep.equal(Object.keys(expectedResponse[0])); + }); + it('handles nobid responses', function() { + let bids = { + 'body': { + 'responses': [] + } + }; + let result = spec.interpretResponse(bids); + expect(result.length).to.equal(0); + }); + }); +}); From a696789dccf454aa0f26dd139b98acd13b0e7d62 Mon Sep 17 00:00:00 2001 From: jsfledd Date: Thu, 30 Sep 2021 05:32:10 -0700 Subject: [PATCH 54/84] Nativo Bid Adapter: update to adUnit param usage (#7517) * Initial nativoBidAdapter document creation (js, md and spec) * Fulling working prebid using nativoBidAdapter. Support for GDPR and CCPA in user syncs. * Added defult size settings based on the largest ad unit. Added response body validation. Added consent to request url qs params. * Changed bidder endpoint url * Changed double quotes to single quotes. * Reverted package-json.lock to remove modifications from PR * Added optional bidder param 'url' so the ad server can force- match an existing placement * Lint fix. Added space after if. * Added new QS param to send various adUnit data to adapter endpopint * Updated unit test for new QS param * Added qs param to keep track of ad unit refreshes * Updated bidMap key default value --- modules/nativoBidAdapter.js | 73 +++++++++++++--------- modules/nativoBidAdapter.md | 1 - test/spec/modules/nativoBidAdapter_spec.js | 53 +++++++++++++++- 3 files changed, 94 insertions(+), 33 deletions(-) diff --git a/modules/nativoBidAdapter.js b/modules/nativoBidAdapter.js index f91a8b6085b..8259c179675 100644 --- a/modules/nativoBidAdapter.js +++ b/modules/nativoBidAdapter.js @@ -1,19 +1,19 @@ -import { isEmpty } from '../src/utils.js'; -import { registerBidder } from '../src/adapters/bidderFactory.js'; -import { BANNER } from '../src/mediaTypes.js'; +import { deepAccess, isEmpty } from '../src/utils.js' +import { registerBidder } from '../src/adapters/bidderFactory.js' +import { BANNER } from '../src/mediaTypes.js' // import { config } from 'src/config' -const BIDDER_CODE = 'nativo'; -const BIDDER_ENDPOINT = 'https://exchange.postrelease.com/prebid'; +const BIDDER_CODE = 'nativo' +const BIDDER_ENDPOINT = 'https://exchange.postrelease.com/prebid' -const GVLID = 263; +const GVLID = 263 -const TIME_TO_LIVE = 360; +const TIME_TO_LIVE = 360 -const SUPPORTED_AD_TYPES = [BANNER]; +const SUPPORTED_AD_TYPES = [BANNER] -const bidRequestMap = {}; -const adUnitsRequested = {}; +const bidRequestMap = {} +const adUnitsRequested = {} // Prebid adapter referrence doc: https://docs.prebid.org/dev-docs/bidder-adaptor.html @@ -30,7 +30,7 @@ export const spec = { * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function (bid) { - return bid.params && !!bid.params.placementId + return true }, /** @@ -42,27 +42,37 @@ export const spec = { * @return ServerRequest Info describing the request to the server. */ buildRequests: function (validBidRequests, bidderRequest) { - const placementIds = [] + const placementIds = new Set() const placmentBidIdMap = {} let placementId, pageUrl validBidRequests.forEach((request) => { - pageUrl = pageUrl || request.params.url // Use the first url value found - placementId = request.params.placementId - placementIds.push(placementId) - placmentBidIdMap[placementId] = { + pageUrl = deepAccess( + request, + 'params.url', + bidderRequest.refererInfo.referer + ) + placementId = deepAccess(request, 'params.placementId') + + if (placementId) { + placementIds.add(placementId) + } + + var key = placementId || request.adUnitCode + placmentBidIdMap[key] = { bidId: request.bidId, size: getLargestSize(request.sizes), } }) bidRequestMap[bidderRequest.bidderRequestId] = placmentBidIdMap - if (!pageUrl) pageUrl = bidderRequest.refererInfo.referer - // Build adUnit data const adUnitData = { adUnits: validBidRequests.map((adUnit) => { // Track if we've already requested for this ad unit code - adUnitsRequested[adUnit.adUnitCode] = adUnitsRequested[adUnit.adUnitCode] !== undefined ? adUnitsRequested[adUnit.adUnitCode]++ : 0 + adUnitsRequested[adUnit.adUnitCode] = + adUnitsRequested[adUnit.adUnitCode] !== undefined + ? adUnitsRequested[adUnit.adUnitCode]++ + : 0 return { adUnitCode: adUnit.adUnitCode, mediaTypes: adUnit.mediaTypes, @@ -72,7 +82,6 @@ export const spec = { // Build QS Params let params = [ - { key: 'ntv_ptd', value: placementIds.toString() }, { key: 'ntv_pb_rid', value: bidderRequest.bidderRequestId }, { key: 'ntv_ppc', @@ -80,14 +89,18 @@ export const spec = { }, { key: 'ntv_dbr', - value: btoa(JSON.stringify(adUnitsRequested)) + value: btoa(JSON.stringify(adUnitsRequested)), }, { key: 'ntv_url', value: encodeURIComponent(pageUrl), - } + }, ] + if (placementIds.size > 0) { + params.unshift({ key: 'ntv_ptd', value: [...placementIds].join(',') }) + } + if (bidderRequest.gdprConsent) { // Put on the beginning of the qs param array params.unshift({ @@ -135,7 +148,7 @@ export const spec = { let bidResponse, adUnit seatbids.forEach((seatbid) => { seatbid.bid.forEach((bid) => { - adUnit = this.getRequestId(body.id, bid.impid) + adUnit = this.getAdUnitData(body.id, bid) bidResponse = { requestId: adUnit.bidId, cpm: bid.price, @@ -268,14 +281,16 @@ export const spec = { /** * Maps Prebid's bidId to Nativo's placementId values per unique bidderRequestId * @param {String} bidderRequestId - The unique ID value associated with the bidderRequest - * @param {String} placementId - The placement ID value from Nativo + * @param {Object} bid - The placement ID value from Nativo * @returns {String} - The bidId value associated with the corresponding placementId */ - getRequestId: function (bidderRequestId, placementId) { - return ( - bidRequestMap[bidderRequestId] && - bidRequestMap[bidderRequestId][placementId] - ) + getAdUnitData: function (bidderRequestId, bid) { + var data = deepAccess(bidRequestMap, `${bidderRequestId}.${bid.impid}`) + + if (data) return data + + var unitCode = deepAccess(bid, 'ext.ad_unit_id') + return deepAccess(bidRequestMap, `${bidderRequestId}.${unitCode}`) }, } registerBidder(spec) diff --git a/modules/nativoBidAdapter.md b/modules/nativoBidAdapter.md index ec0980aae50..f83fb45b52e 100644 --- a/modules/nativoBidAdapter.md +++ b/modules/nativoBidAdapter.md @@ -29,7 +29,6 @@ var adUnits = [ bids: [{ bidder: 'nativo', params: { - placementId: 1125609, url: 'https://test-sites.internal.nativo.net/testing/prebid_adpater.html' } }] diff --git a/test/spec/modules/nativoBidAdapter_spec.js b/test/spec/modules/nativoBidAdapter_spec.js index 4202b7c6f91..dfc9f5b99b3 100644 --- a/test/spec/modules/nativoBidAdapter_spec.js +++ b/test/spec/modules/nativoBidAdapter_spec.js @@ -26,11 +26,11 @@ describe('nativoBidAdapterTests', function () { expect(spec.isBidRequestValid(bid)).to.equal(true) }) - it('should return false when required params are not passed', function () { + it('should return true when params are not passed', function () { let bid2 = Object.assign({}, bid) delete bid2.params bid2.params = {} - expect(spec.isBidRequestValid(bid2)).to.equal(false) + expect(spec.isBidRequestValid(bid2)).to.equal(true) }) }) @@ -129,7 +129,12 @@ describe('interpretResponse', function () { } // mock - spec.getRequestId = () => 123456 + spec.getAdUnitData = () => { + return { + bidId: 123456, + sizes: [300, 250], + } + } let result = spec.interpretResponse({ body: response }, { bidderRequest }) expect(Object.keys(result[0])).to.have.deep.members( @@ -232,3 +237,45 @@ describe('getUserSyncs', function () { ) }) }) + +describe('getAdUnitData', () => { + afterEach(() => { + if (window.bidRequestMap) delete window.bidRequestMap + }) + + it('Matches placementId value', () => { + const adUnitData = { + bidId: 123456, + sizes: [300, 250], + } + + window.bidRequestMap = { + 9876543: { + 12345: adUnitData, + }, + } + + const data = spec.getAdUnitData(9876543, { impid: 12345 }) + expect(Object.keys(data)).to.have.deep.members( + Object.keys(adUnitData) + ) + }) + + it('Falls back to ad unit code value', () => { + const adUnitData = { + bidId: 123456, + sizes: [300, 250], + } + + window.bidRequestMap = { + 9876543: { + '#test-code': adUnitData, + }, + } + + const data = spec.getAdUnitData(9876543, { impid: 12345, ext: { ad_unit_code: '#test-code' } }) + expect(Object.keys(data)).to.have.deep.members( + Object.keys(adUnitData) + ) + }) +}) From 6d4daa437c2002a483aaf4003848f64916d35150 Mon Sep 17 00:00:00 2001 From: Paul Yang Date: Thu, 30 Sep 2021 06:14:59 -0700 Subject: [PATCH 55/84] PubLink id system adds params for site id and api key (#7515) --- modules/publinkIdSystem.js | 7 ++++- modules/publinkIdSystem.md | 9 ++++-- test/spec/modules/publinkIdSystem_spec.js | 37 +++++++++++++++++------ 3 files changed, 41 insertions(+), 12 deletions(-) diff --git a/modules/publinkIdSystem.js b/modules/publinkIdSystem.js index 9acc741f7da..299158a175e 100644 --- a/modules/publinkIdSystem.js +++ b/modules/publinkIdSystem.js @@ -19,7 +19,7 @@ const PUBLINK_S2S_COOKIE = '_publink_srv'; export const storage = getStorageManager(GVLID); function isHex(s) { - return (typeof s === 'string' && /^[A-F0-9]+$/i.test(s)); + return /^[A-F0-9]+$/i.test(s); } function publinkIdUrl(params, consentData) { @@ -29,11 +29,16 @@ function publinkIdUrl(params, consentData) { mpn: 'Prebid.js', mpv: '$prebid.version$', }; + if (consentData) { url.search.gdpr = (consentData.gdprApplies) ? 1 : 0; url.search.gdpr_consent = consentData.consentString; } + if (params.site_id) { url.search.sid = params.site_id; } + + if (params.api_key) { url.search.apikey = params.api_key; } + const usPrivacyString = uspDataHandler.getConsentData(); if (usPrivacyString && typeof usPrivacyString === 'string') { url.search.us_privacy = usPrivacyString; diff --git a/modules/publinkIdSystem.md b/modules/publinkIdSystem.md index 669828322a5..263ce490529 100644 --- a/modules/publinkIdSystem.md +++ b/modules/publinkIdSystem.md @@ -7,7 +7,10 @@ Publink user id module | Param Name | Required | Type | Description | Example | | --- | --- | --- | --- | --- | | name | Yes | String | module identifier | `"publinkId"` | -| params.e | Yes | String | hashed email address | `"e80b5017098950fc58aad83c8c14978e"` | +| params.e | Yes | String | hashed email address | `"7D320454942620664D96EF78ED4E3A2A"` | +| params.api_key | Yes | String | api key for access | `"7ab62359-bdc0-4095-b573-ef474fb55d24"` | +| params.site_id | Yes | String | site identifier | `"123456"` | + ### Example configuration for Publink ``` @@ -20,7 +23,9 @@ pbjs.setConfig({ type: "html5" }, params: { - e: "e80b5017098950fc58aad83c8c14978e", // example hashed email (md5) + e: "7D320454942620664D96EF78ED4E3A2A", // example hashed email (md5) + site_id: "123456", // provided by Epsilon + api_key: "7ab62359-bdc0-4095-b573-ef474fb55d2" // provided by Epsilon } }], } diff --git a/test/spec/modules/publinkIdSystem_spec.js b/test/spec/modules/publinkIdSystem_spec.js index 0680e02e3fa..aa6b669d773 100644 --- a/test/spec/modules/publinkIdSystem_spec.js +++ b/test/spec/modules/publinkIdSystem_spec.js @@ -3,6 +3,7 @@ import {getStorageManager} from '../../../src/storageManager'; import {server} from 'test/mocks/xhr.js'; import sinon from 'sinon'; import {uspDataHandler} from '../../../src/adapterManager'; +import {parseUrl} from '../../../src/utils'; export const storage = getStorageManager(24); const TEST_COOKIE_VALUE = 'cookievalue'; @@ -83,14 +84,22 @@ describe('PublinkIdSystem', () => { }); it('Fetch with consent data', () => { - const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7'}}; + const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7', site_id: '102030'}}; const consentData = {gdprApplies: 1, consentString: 'myconsentstring'}; let submoduleCallback = publinkIdSubmodule.getId(config, consentData).callback; submoduleCallback(callbackSpy); - let request = server.requests[0]; - request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$&gdpr=1&gdpr_consent=myconsentstring'); + const request = server.requests[0]; + const parsed = parseUrl(request.url); + + expect(parsed.hostname).to.equal('proc.ad.cpe.dotomi.com'); + expect(parsed.pathname).to.equal('/cvx/client/sync/publink'); + expect(parsed.search.mpn).to.equal('Prebid.js'); + expect(parsed.search.mpv).to.equal('$prebid.version$'); + expect(parsed.search.gdpr).to.equal('1'); + expect(parsed.search.gdpr_consent).to.equal('myconsentstring'); + expect(parsed.search.sid).to.equal('102030'); + expect(parsed.search.apikey).to.be.undefined; request.respond(200, {}, JSON.stringify(serverResponse)); expect(callbackSpy.calledOnce).to.be.true; @@ -103,8 +112,12 @@ describe('PublinkIdSystem', () => { submoduleCallback(callbackSpy); let request = server.requests[0]; - request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$'); + const parsed = parseUrl(request.url); + + expect(parsed.hostname).to.equal('proc.ad.cpe.dotomi.com'); + expect(parsed.pathname).to.equal('/cvx/client/sync/publink'); + expect(parsed.search.mpn).to.equal('Prebid.js'); + expect(parsed.search.mpv).to.equal('$prebid.version$'); request.respond(204, {}, JSON.stringify(serverResponse)); expect(callbackSpy.called).to.be.false; @@ -133,13 +146,19 @@ describe('PublinkIdSystem', () => { }); it('Fetch with usprivacy data', () => { - const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7'}}; + const config = {storage: {type: 'cookie'}, params: {e: 'ca11c0ca7', api_key: 'abcdefg'}}; let submoduleCallback = publinkIdSubmodule.getId(config).callback; submoduleCallback(callbackSpy); let request = server.requests[0]; - request.url = request.url.replace(':443', ''); - expect(request.url).to.equal('https://proc.ad.cpe.dotomi.com/cvx/client/sync/publink?deh=ca11c0ca7&mpn=Prebid.js&mpv=$prebid.version$&us_privacy=1YNN'); + const parsed = parseUrl(request.url); + + expect(parsed.hostname).to.equal('proc.ad.cpe.dotomi.com'); + expect(parsed.pathname).to.equal('/cvx/client/sync/publink'); + expect(parsed.search.mpn).to.equal('Prebid.js'); + expect(parsed.search.mpv).to.equal('$prebid.version$'); + expect(parsed.search.us_privacy).to.equal('1YNN'); + expect(parsed.search.apikey).to.equal('abcdefg'); request.respond(200, {}, JSON.stringify(serverResponse)); expect(callbackSpy.calledOnce).to.be.true; From 34c189d97d7c8af0dd73ae24325f53d1d3613f30 Mon Sep 17 00:00:00 2001 From: Lisa Benmore Date: Thu, 30 Sep 2021 08:46:56 -0700 Subject: [PATCH 56/84] Gumgum Bid Adapter: use nearest matching h/w dimensions from bid request (#7505) * Gumgum: ADTS-157 use nearest matching h/w dimensions from bid request * updated method calls from utils --- modules/gumgumBidAdapter.js | 10 ++++++++-- test/spec/modules/gumgumBidAdapter_spec.js | 23 +++++++++++++++++----- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/modules/gumgumBidAdapter.js b/modules/gumgumBidAdapter.js index 756d204e00d..76fb7023bb1 100644 --- a/modules/gumgumBidAdapter.js +++ b/modules/gumgumBidAdapter.js @@ -1,5 +1,6 @@ -import { logError, logWarn, parseSizesInput, _each, deepAccess } from '../src/utils.js'; import { BANNER, VIDEO } from '../src/mediaTypes.js'; +import { _each, deepAccess, logError, logWarn, parseSizesInput } from '../src/utils.js'; + import { config } from '../src/config.js' import { getStorageManager } from '../src/storageManager.js'; import includes from 'core-js-pure/features/array/includes'; @@ -488,7 +489,12 @@ function interpretResponse(serverResponse, bidRequest) { } else if (product === 5 && includes(sizes, '1x1')) { sizes = ['1x1']; } else if (product === 2 && includes(sizes, '1x1')) { - sizes = responseWidth && responseHeight ? [`${responseWidth}x${responseHeight}`] : parseSizesInput(bidRequest.sizes) + const requestSizesThatMatchResponse = (bidRequest.sizes && bidRequest.sizes.reduce((result, current) => { + const [ width, height ] = current; + if (responseWidth === width || responseHeight === height) result.push(current.join('x')); + return result + }, [])) || []; + sizes = requestSizesThatMatchResponse.length ? requestSizesThatMatchResponse : parseSizesInput(bidRequest.sizes) } let [width, height] = sizes[0].split('x'); diff --git a/test/spec/modules/gumgumBidAdapter_spec.js b/test/spec/modules/gumgumBidAdapter_spec.js index e11123729e0..713bd514c0c 100644 --- a/test/spec/modules/gumgumBidAdapter_spec.js +++ b/test/spec/modules/gumgumBidAdapter_spec.js @@ -683,11 +683,24 @@ describe('gumgumAdapter', function () { expect(result[0].height).to.equal('1'); }); - it('uses response width and height for inscreen product', function () { - const result = spec.interpretResponse({ body: serverResponse }, bidRequest)[0]; - expect(result.width).to.equal(serverResponse.ad.width.toString()); - expect(result.height).to.equal(serverResponse.ad.height.toString()); - }); + it('uses request size that nearest matches response size for in-screen', function () { + const request = { ...bidRequest }; + const body = { ...serverResponse }; + const expectedSize = [ 300, 50 ]; + let result; + + request.pi = 2; + request.sizes.unshift(expectedSize); + + // typical ad server response values for in-screen + body.ad.width = 300; + body.ad.height = 100; + + result = spec.interpretResponse({ body }, request)[0]; + + expect(result.width = expectedSize[0]); + expect(result.height = expectedSize[1]); + }) it('defaults to use bidRequest sizes', function () { const { ad, jcsi, pag, thms, meta } = serverResponse From 60a12e0780ebe2de2b0f1f7af41b72743402333e Mon Sep 17 00:00:00 2001 From: Manasi Date: Thu, 30 Sep 2021 22:08:57 +0530 Subject: [PATCH 57/84] Pubmatic Bid Adapter: add support for JW player (#7450) * changes to support jwplayer segment data in pubmatic s2s endpoint * remove additional '|' getting added if dctr is blank * changes utils.convertType to remove reference to utils --- modules/pubmaticBidAdapter.js | 19 +- test/spec/modules/pubmaticBidAdapter_spec.js | 178 +++++++++++++++++++ 2 files changed, 191 insertions(+), 6 deletions(-) diff --git a/modules/pubmaticBidAdapter.js b/modules/pubmaticBidAdapter.js index fa1f04a25e2..4c182c214a3 100644 --- a/modules/pubmaticBidAdapter.js +++ b/modules/pubmaticBidAdapter.js @@ -605,7 +605,7 @@ function _addDealCustomTargetings(imp, bid) { } } -function _addJWPlayerSegmentData(imp, bid) { +function _addJWPlayerSegmentData(imp, bid, isS2S) { var jwSegData = (bid.rtd && bid.rtd.jwplayer && bid.rtd.jwplayer.targeting) || undefined; var jwPlayerData = ''; const jwMark = 'jw-'; @@ -619,10 +619,15 @@ function _addJWPlayerSegmentData(imp, bid) { for (var i = 0; i < maxLength; i++) { jwPlayerData += '|' + jwMark + jwSegData.segments[i] + '=1'; } - const ext = imp.ext; - (ext && ext.key_val === undefined) - ? ext.key_val = jwPlayerData - : ext.key_val += '|' + jwPlayerData; + + var ext; + + if (isS2S) { + (imp.dctr === undefined || imp.dctr.length == 0) ? imp.dctr = jwPlayerData : imp.dctr += '|' + jwPlayerData; + } else { + ext = imp.ext; + ext && ext.key_val === undefined ? ext.key_val = jwPlayerData : ext.key_val += '|' + jwPlayerData; + } } function _createImpressionObject(bid, conf) { @@ -1322,7 +1327,9 @@ export const spec = { * @param {Boolean} isOpenRtb boolean to check openrtb2 protocol * @return {Object} params bid params */ - transformBidParams: function (params, isOpenRtb) { + + transformBidParams: function (params, isOpenRtb, adUnit, bidRequests) { + _addJWPlayerSegmentData(params, adUnit.bids[0], true); return convertTypes({ 'publisherId': 'string', 'adSlot': 'string' diff --git a/test/spec/modules/pubmaticBidAdapter_spec.js b/test/spec/modules/pubmaticBidAdapter_spec.js index 54da555e6ce..47b9c984ff5 100644 --- a/test/spec/modules/pubmaticBidAdapter_spec.js +++ b/test/spec/modules/pubmaticBidAdapter_spec.js @@ -3644,5 +3644,183 @@ describe('PubMatic adapter', function () { }]); }); }); + + describe('JW player segment data for S2S', function() { + let sandbox = sinon.sandbox.create(); + beforeEach(function () { + sandbox = sinon.sandbox.create(); + }); + afterEach(function() { + sandbox.restore(); + }); + it('Should append JW player segment data to dctr values in auction endpoint', function() { + var videoAdUnit = { + 'bidderCode': 'pubmatic', + 'bids': [ + { + 'bidder': 'pubmatic', + 'params': { + 'publisherId': '156276', + 'adSlot': 'pubmatic_video2', + 'dctr': 'key1=123|key2=345', + 'pmzoneid': '1243', + 'video': { + 'mimes': ['video/mp4', 'video/x-flv'], + 'skippable': true, + 'minduration': 5, + 'maxduration': 30, + 'startdelay': 5, + 'playbackmethod': [1, 3], + 'api': [1, 2], + 'protocols': [2, 3], + 'battr': [13, 14], + 'linearity': 1, + 'placement': 2, + 'minbitrate': 10, + 'maxbitrate': 10 + } + }, + 'rtd': { + 'jwplayer': { + 'targeting': { + 'segments': ['80011026', '80011035'], + 'content': { + 'id': 'jw_d9J2zcaA' + } + } + } + }, + 'bid_id': '17a6771be26cc4', + 'ortb2Imp': { + 'ext': { + 'data': { + 'pbadslot': 'abcd', + 'jwTargeting': { + 'playerID': 'myElement1', + 'mediaID': 'd9J2zcaA' + } + } + } + } + } + ], + 'auctionStart': 1630923178417, + 'timeout': 1000, + 'src': 's2s' + } + + spec.transformBidParams(bidRequests[0].params, true, videoAdUnit); + expect(bidRequests[0].params.dctr).to.equal('key1:val1,val2|key2:val1|jw-id=jw_d9J2zcaA|jw-80011026=1|jw-80011035=1'); + }); + it('Should send only JW player segment data in auction endpoint, if dctr is missing', function() { + var videoAdUnit = { + 'bidderCode': 'pubmatic', + 'bids': [ + { + 'bidder': 'pubmatic', + 'params': { + 'publisherId': '156276', + 'adSlot': 'pubmatic_video2', + 'dctr': 'key1=123|key2=345', + 'pmzoneid': '1243', + 'video': { + 'mimes': ['video/mp4', 'video/x-flv'], + 'skippable': true, + 'minduration': 5, + 'maxduration': 30, + 'startdelay': 5, + 'playbackmethod': [1, 3], + 'api': [1, 2], + 'protocols': [2, 3], + 'battr': [13, 14], + 'linearity': 1, + 'placement': 2, + 'minbitrate': 10, + 'maxbitrate': 10 + } + }, + 'rtd': { + 'jwplayer': { + 'targeting': { + 'segments': ['80011026', '80011035'], + 'content': { + 'id': 'jw_d9J2zcaA' + } + } + } + }, + 'bid_id': '17a6771be26cc4', + 'ortb2Imp': { + 'ext': { + 'data': { + 'pbadslot': 'abcd', + 'jwTargeting': { + 'playerID': 'myElement1', + 'mediaID': 'd9J2zcaA' + } + } + } + } + } + ], + 'auctionStart': 1630923178417, + 'timeout': 1000, + 'src': 's2s' + } + + delete bidRequests[0].params.dctr; + spec.transformBidParams(bidRequests[0].params, true, videoAdUnit); + expect(bidRequests[0].params.dctr).to.equal('jw-id=jw_d9J2zcaA|jw-80011026=1|jw-80011035=1'); + }); + + it('Should not send any JW player segment data in auction endpoint, if it is not available', function() { + var videoAdUnit = { + 'bidderCode': 'pubmatic', + 'bids': [ + { + 'bidder': 'pubmatic', + 'params': { + 'publisherId': '156276', + 'adSlot': 'pubmatic_video2', + 'dctr': 'key1=123|key2=345', + 'pmzoneid': '1243', + 'video': { + 'mimes': ['video/mp4', 'video/x-flv'], + 'skippable': true, + 'minduration': 5, + 'maxduration': 30, + 'startdelay': 5, + 'playbackmethod': [1, 3], + 'api': [1, 2], + 'protocols': [2, 3], + 'battr': [13, 14], + 'linearity': 1, + 'placement': 2, + 'minbitrate': 10, + 'maxbitrate': 10 + } + }, + 'bid_id': '17a6771be26cc4', + 'ortb2Imp': { + 'ext': { + 'data': { + 'pbadslot': 'abcd', + 'jwTargeting': { + 'playerID': 'myElement1', + 'mediaID': 'd9J2zcaA' + } + } + } + } + } + ], + 'auctionStart': 1630923178417, + 'timeout': 1000, + 'src': 's2s' + } + spec.transformBidParams(bidRequests[0].params, true, videoAdUnit); + expect(bidRequests[0].params.dctr).to.equal('key1:val1,val2|key2:val1'); + }); + }) }); }); From 9ba675043d8ff28e0b2468759080b3aa338feae0 Mon Sep 17 00:00:00 2001 From: Sasan Farrokh Date: Thu, 30 Sep 2021 20:09:34 +0330 Subject: [PATCH 58/84] fix(vidoomyBidAdapter): macro replacement and gdprConsent null fix (#7518) Co-authored-by: Sasan Farrokh --- modules/vidoomyBidAdapter.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/vidoomyBidAdapter.js b/modules/vidoomyBidAdapter.js index afb06e06d12..90a8cfff44d 100644 --- a/modules/vidoomyBidAdapter.js +++ b/modules/vidoomyBidAdapter.js @@ -93,8 +93,8 @@ const buildRequests = (validBidRequests, bidderRequest) => { xhr.open('GET', COOKIE_SYNC_JSON) xhr.addEventListener('load', function () { const macro = Macro({ - gpdr: bidderRequest.gdprConsent.gdprApplies, - gpdr_consent: bidderRequest.gdprConsent.consentString + gpdr: bidderRequest.gdprConsent ? bidderRequest.gdprConsent.gdprApplies : '0', + gpdr_consent: bidderRequest.gdprConsent ? bidderRequest.gdprConsent.consentString : '', }); JSON.parse(this.responseText).filter(Boolean).forEach(url => { firePixel(macro.replace(url)) @@ -248,6 +248,7 @@ function Macro (obj) { /{{\s*([a-zA-Z0-9_]+)\s*}}/g, /\$\$\s*([a-zA-Z0-9_]+)\s*\$\$/g, /\[\s*([a-zA-Z0-9_]+)\s*\]/g, + /\{\s*([a-zA-Z0-9_]+)\s*\}/g, ]; regexes.forEach(regex => { string = string.replace(regex, (str, x) => { From 0ee71d2e2a68159dad931e00bf7d3af18bcf2833 Mon Sep 17 00:00:00 2001 From: relaido <63339139+relaido@users.noreply.github.com> Date: Fri, 1 Oct 2021 01:59:41 +0900 Subject: [PATCH 59/84] Relaido Bid Adapter: support imuid module (#7422) * add relaido adapter * remove event listener * fixed UserSyncs and e.data * fix conflicts * supports imuid module Co-authored-by: ishigami_shingo Co-authored-by: cmertv-sishigami Co-authored-by: t_bun --- modules/relaidoBidAdapter.js | 10 ++++-- test/spec/modules/relaidoBidAdapter_spec.js | 40 ++++++++++----------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/modules/relaidoBidAdapter.js b/modules/relaidoBidAdapter.js index 4df13b52a39..a3b83e73ae3 100644 --- a/modules/relaidoBidAdapter.js +++ b/modules/relaidoBidAdapter.js @@ -6,7 +6,7 @@ import { getStorageManager } from '../src/storageManager.js'; const BIDDER_CODE = 'relaido'; const BIDDER_DOMAIN = 'api.relaido.jp'; -const ADAPTER_VERSION = '1.0.5'; +const ADAPTER_VERSION = '1.0.6'; const DEFAULT_TTL = 300; const UUID_KEY = 'relaido_uuid'; @@ -68,9 +68,15 @@ function buildRequests(validBidRequests, bidderRequest) { media_type: mediaType, uuid: uuid, width: width, - height: height + height: height, + pv: '$prebid.version$' }; + const imuid = utils.deepAccess(bidRequest, 'userId.imuid'); + if (imuid) { + payload.imuid = imuid; + } + // It may not be encoded, so add it at the end of the payload payload.ref = bidderRequest.refererInfo.referer; diff --git a/test/spec/modules/relaidoBidAdapter_spec.js b/test/spec/modules/relaidoBidAdapter_spec.js index e372c67bb4e..c6e2a9ae5d5 100644 --- a/test/spec/modules/relaidoBidAdapter_spec.js +++ b/test/spec/modules/relaidoBidAdapter_spec.js @@ -20,8 +20,12 @@ describe('RelaidoAdapter', function () { let bidderRequest; let serverResponse; let serverRequest; + let generateUUIDStub; + let triggerPixelStub; beforeEach(function () { + generateUUIDStub = sinon.stub(utils, 'generateUUID').returns(relaido_uuid); + triggerPixelStub = sinon.stub(utils, 'triggerPixel'); bidRequest = { bidder: 'relaido', params: { @@ -72,6 +76,10 @@ describe('RelaidoAdapter', function () { mediaType: 'video', }; }); + afterEach(() => { + generateUUIDStub.restore(); + triggerPixelStub.restore(); + }); describe('spec.isBidRequestValid', function () { it('should return true when the required params are passed by video', function () { @@ -207,6 +215,7 @@ describe('RelaidoAdapter', function () { expect(request.data.uuid).to.equal(relaido_uuid); expect(request.data.width).to.equal(bidRequest.mediaTypes.video.playerSize[0][0]); expect(request.data.height).to.equal(bidRequest.mediaTypes.video.playerSize[0][1]); + expect(request.data.pv).to.equal('$prebid.version$'); }); it('should build bid requests by banner', function () { @@ -251,8 +260,6 @@ describe('RelaidoAdapter', function () { expect(bidRequests).to.have.lengthOf(1); const request = bidRequests[0]; - // eslint-disable-next-line no-console - console.log(bidRequests); expect(request.width).to.equal(1); }); @@ -264,6 +271,15 @@ describe('RelaidoAdapter', function () { expect(keys[0]).to.equal('version'); expect(keys[keys.length - 1]).to.equal('ref'); }); + + it('should get imuid', function () { + bidRequest.userId = {} + bidRequest.userId.imuid = 'i.tjHcK_7fTcqnbrS_YA2vaw'; + const bidRequests = spec.buildRequests([bidRequest], bidderRequest); + expect(bidRequests).to.have.lengthOf(1); + const request = bidRequests[0]; + expect(request.data.imuid).to.equal('i.tjHcK_7fTcqnbrS_YA2vaw'); + }); }); describe('spec.interpretResponse', function () { @@ -350,14 +366,6 @@ describe('RelaidoAdapter', function () { }); describe('spec.onBidWon', function () { - let stub; - beforeEach(() => { - stub = sinon.stub(utils, 'triggerPixel'); - }); - afterEach(() => { - stub.restore(); - }); - it('Should create nurl pixel if bid nurl', function () { let bid = { bidder: bidRequest.bidder, @@ -371,7 +379,7 @@ describe('RelaidoAdapter', function () { ref: window.location.href, } spec.onBidWon(bid); - const parser = utils.parseUrl(stub.getCall(0).args[0]); + const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/win.gif'); @@ -387,14 +395,6 @@ describe('RelaidoAdapter', function () { }); describe('spec.onTimeout', function () { - let stub; - beforeEach(() => { - stub = sinon.stub(utils, 'triggerPixel'); - }); - afterEach(() => { - stub.restore(); - }); - it('Should create nurl pixel if bid nurl', function () { const data = [{ bidder: bidRequest.bidder, @@ -405,7 +405,7 @@ describe('RelaidoAdapter', function () { timeout: bidderRequest.timeout, }]; spec.onTimeout(data); - const parser = utils.parseUrl(stub.getCall(0).args[0]); + const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/timeout.gif'); From d7fc1a74ad69f6fbfcf8ff2e0df1eaf2683a4019 Mon Sep 17 00:00:00 2001 From: Chris Huie Date: Thu, 30 Sep 2021 10:02:45 -0700 Subject: [PATCH 60/84] Revert "Relaido Bid Adapter: support imuid module (#7422)" (#7520) This reverts commit 0ee71d2e2a68159dad931e00bf7d3af18bcf2833. --- modules/relaidoBidAdapter.js | 10 ++---- test/spec/modules/relaidoBidAdapter_spec.js | 40 ++++++++++----------- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/modules/relaidoBidAdapter.js b/modules/relaidoBidAdapter.js index a3b83e73ae3..4df13b52a39 100644 --- a/modules/relaidoBidAdapter.js +++ b/modules/relaidoBidAdapter.js @@ -6,7 +6,7 @@ import { getStorageManager } from '../src/storageManager.js'; const BIDDER_CODE = 'relaido'; const BIDDER_DOMAIN = 'api.relaido.jp'; -const ADAPTER_VERSION = '1.0.6'; +const ADAPTER_VERSION = '1.0.5'; const DEFAULT_TTL = 300; const UUID_KEY = 'relaido_uuid'; @@ -68,15 +68,9 @@ function buildRequests(validBidRequests, bidderRequest) { media_type: mediaType, uuid: uuid, width: width, - height: height, - pv: '$prebid.version$' + height: height }; - const imuid = utils.deepAccess(bidRequest, 'userId.imuid'); - if (imuid) { - payload.imuid = imuid; - } - // It may not be encoded, so add it at the end of the payload payload.ref = bidderRequest.refererInfo.referer; diff --git a/test/spec/modules/relaidoBidAdapter_spec.js b/test/spec/modules/relaidoBidAdapter_spec.js index c6e2a9ae5d5..e372c67bb4e 100644 --- a/test/spec/modules/relaidoBidAdapter_spec.js +++ b/test/spec/modules/relaidoBidAdapter_spec.js @@ -20,12 +20,8 @@ describe('RelaidoAdapter', function () { let bidderRequest; let serverResponse; let serverRequest; - let generateUUIDStub; - let triggerPixelStub; beforeEach(function () { - generateUUIDStub = sinon.stub(utils, 'generateUUID').returns(relaido_uuid); - triggerPixelStub = sinon.stub(utils, 'triggerPixel'); bidRequest = { bidder: 'relaido', params: { @@ -76,10 +72,6 @@ describe('RelaidoAdapter', function () { mediaType: 'video', }; }); - afterEach(() => { - generateUUIDStub.restore(); - triggerPixelStub.restore(); - }); describe('spec.isBidRequestValid', function () { it('should return true when the required params are passed by video', function () { @@ -215,7 +207,6 @@ describe('RelaidoAdapter', function () { expect(request.data.uuid).to.equal(relaido_uuid); expect(request.data.width).to.equal(bidRequest.mediaTypes.video.playerSize[0][0]); expect(request.data.height).to.equal(bidRequest.mediaTypes.video.playerSize[0][1]); - expect(request.data.pv).to.equal('$prebid.version$'); }); it('should build bid requests by banner', function () { @@ -260,6 +251,8 @@ describe('RelaidoAdapter', function () { expect(bidRequests).to.have.lengthOf(1); const request = bidRequests[0]; + // eslint-disable-next-line no-console + console.log(bidRequests); expect(request.width).to.equal(1); }); @@ -271,15 +264,6 @@ describe('RelaidoAdapter', function () { expect(keys[0]).to.equal('version'); expect(keys[keys.length - 1]).to.equal('ref'); }); - - it('should get imuid', function () { - bidRequest.userId = {} - bidRequest.userId.imuid = 'i.tjHcK_7fTcqnbrS_YA2vaw'; - const bidRequests = spec.buildRequests([bidRequest], bidderRequest); - expect(bidRequests).to.have.lengthOf(1); - const request = bidRequests[0]; - expect(request.data.imuid).to.equal('i.tjHcK_7fTcqnbrS_YA2vaw'); - }); }); describe('spec.interpretResponse', function () { @@ -366,6 +350,14 @@ describe('RelaidoAdapter', function () { }); describe('spec.onBidWon', function () { + let stub; + beforeEach(() => { + stub = sinon.stub(utils, 'triggerPixel'); + }); + afterEach(() => { + stub.restore(); + }); + it('Should create nurl pixel if bid nurl', function () { let bid = { bidder: bidRequest.bidder, @@ -379,7 +371,7 @@ describe('RelaidoAdapter', function () { ref: window.location.href, } spec.onBidWon(bid); - const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); + const parser = utils.parseUrl(stub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/win.gif'); @@ -395,6 +387,14 @@ describe('RelaidoAdapter', function () { }); describe('spec.onTimeout', function () { + let stub; + beforeEach(() => { + stub = sinon.stub(utils, 'triggerPixel'); + }); + afterEach(() => { + stub.restore(); + }); + it('Should create nurl pixel if bid nurl', function () { const data = [{ bidder: bidRequest.bidder, @@ -405,7 +405,7 @@ describe('RelaidoAdapter', function () { timeout: bidderRequest.timeout, }]; spec.onTimeout(data); - const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); + const parser = utils.parseUrl(stub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/timeout.gif'); From cd53743b3a9736fd0492c518237d26b0327fe598 Mon Sep 17 00:00:00 2001 From: Chris Huie Date: Thu, 30 Sep 2021 10:43:49 -0700 Subject: [PATCH 61/84] Relaido Bid Adapter: support imuid (with utils fix after revert) (#7521) * Relaido Bid Adapter: support imuid `utils.` no longer needed because of specific import of functions * update testing * fix spaces * fix test linting * fix blank line padding --- modules/relaidoBidAdapter.js | 10 ++++- test/spec/modules/relaidoBidAdapter_spec.js | 41 +++++++++++---------- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/modules/relaidoBidAdapter.js b/modules/relaidoBidAdapter.js index 4df13b52a39..16e01f80819 100644 --- a/modules/relaidoBidAdapter.js +++ b/modules/relaidoBidAdapter.js @@ -6,7 +6,7 @@ import { getStorageManager } from '../src/storageManager.js'; const BIDDER_CODE = 'relaido'; const BIDDER_DOMAIN = 'api.relaido.jp'; -const ADAPTER_VERSION = '1.0.5'; +const ADAPTER_VERSION = '1.0.6'; const DEFAULT_TTL = 300; const UUID_KEY = 'relaido_uuid'; @@ -68,9 +68,15 @@ function buildRequests(validBidRequests, bidderRequest) { media_type: mediaType, uuid: uuid, width: width, - height: height + height: height, + pv: '$prebid.version$' }; + const imuid = deepAccess(bidRequest, 'userId.imuid'); + if (imuid) { + payload.imuid = imuid; + } + // It may not be encoded, so add it at the end of the payload payload.ref = bidderRequest.refererInfo.referer; diff --git a/test/spec/modules/relaidoBidAdapter_spec.js b/test/spec/modules/relaidoBidAdapter_spec.js index e372c67bb4e..868b1856c34 100644 --- a/test/spec/modules/relaidoBidAdapter_spec.js +++ b/test/spec/modules/relaidoBidAdapter_spec.js @@ -20,8 +20,12 @@ describe('RelaidoAdapter', function () { let bidderRequest; let serverResponse; let serverRequest; + let generateUUIDStub; + let triggerPixelStub; beforeEach(function () { + generateUUIDStub = sinon.stub(utils, 'generateUUID').returns(relaido_uuid); + triggerPixelStub = sinon.stub(utils, 'triggerPixel'); bidRequest = { bidder: 'relaido', params: { @@ -73,6 +77,11 @@ describe('RelaidoAdapter', function () { }; }); + afterEach(() => { + generateUUIDStub.restore(); + triggerPixelStub.restore(); + }); + describe('spec.isBidRequestValid', function () { it('should return true when the required params are passed by video', function () { expect(spec.isBidRequestValid(bidRequest)).to.equal(true); @@ -207,6 +216,7 @@ describe('RelaidoAdapter', function () { expect(request.data.uuid).to.equal(relaido_uuid); expect(request.data.width).to.equal(bidRequest.mediaTypes.video.playerSize[0][0]); expect(request.data.height).to.equal(bidRequest.mediaTypes.video.playerSize[0][1]); + expect(request.data.pv).to.equal('$prebid.version$'); }); it('should build bid requests by banner', function () { @@ -251,8 +261,6 @@ describe('RelaidoAdapter', function () { expect(bidRequests).to.have.lengthOf(1); const request = bidRequests[0]; - // eslint-disable-next-line no-console - console.log(bidRequests); expect(request.width).to.equal(1); }); @@ -264,6 +272,15 @@ describe('RelaidoAdapter', function () { expect(keys[0]).to.equal('version'); expect(keys[keys.length - 1]).to.equal('ref'); }); + + it('should get imuid', function () { + bidRequest.userId = {} + bidRequest.userId.imuid = 'i.tjHcK_7fTcqnbrS_YA2vaw'; + const bidRequests = spec.buildRequests([bidRequest], bidderRequest); + expect(bidRequests).to.have.lengthOf(1); + const request = bidRequests[0]; + expect(request.data.imuid).to.equal('i.tjHcK_7fTcqnbrS_YA2vaw'); + }); }); describe('spec.interpretResponse', function () { @@ -350,14 +367,6 @@ describe('RelaidoAdapter', function () { }); describe('spec.onBidWon', function () { - let stub; - beforeEach(() => { - stub = sinon.stub(utils, 'triggerPixel'); - }); - afterEach(() => { - stub.restore(); - }); - it('Should create nurl pixel if bid nurl', function () { let bid = { bidder: bidRequest.bidder, @@ -371,7 +380,7 @@ describe('RelaidoAdapter', function () { ref: window.location.href, } spec.onBidWon(bid); - const parser = utils.parseUrl(stub.getCall(0).args[0]); + const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/win.gif'); @@ -387,14 +396,6 @@ describe('RelaidoAdapter', function () { }); describe('spec.onTimeout', function () { - let stub; - beforeEach(() => { - stub = sinon.stub(utils, 'triggerPixel'); - }); - afterEach(() => { - stub.restore(); - }); - it('Should create nurl pixel if bid nurl', function () { const data = [{ bidder: bidRequest.bidder, @@ -405,7 +406,7 @@ describe('RelaidoAdapter', function () { timeout: bidderRequest.timeout, }]; spec.onTimeout(data); - const parser = utils.parseUrl(stub.getCall(0).args[0]); + const parser = utils.parseUrl(triggerPixelStub.getCall(0).args[0]); const query = parser.search; expect(parser.hostname).to.equal('api.relaido.jp'); expect(parser.pathname).to.equal('/tr/v1/prebid/timeout.gif'); From 7e558a5689e379f2ea4662f09fd71818ddafe744 Mon Sep 17 00:00:00 2001 From: Denislavrov <31471151+Denislavrov@users.noreply.github.com> Date: Fri, 1 Oct 2021 00:42:38 +0300 Subject: [PATCH 62/84] Mytarget Bid Adapter : update adapter to comply with Prebid 5 (#7397) * Add myTargetBitAdapter for Prebid 5.0 * added support advertiserDomains * fixed utils import Co-authored-by: Denis Lavrov --- modules/mytargetBidAdapter.js | 112 +++++++++++ test/spec/modules/mytargetBidAdapter_spec.js | 199 +++++++++++++++++++ 2 files changed, 311 insertions(+) create mode 100644 modules/mytargetBidAdapter.js create mode 100644 test/spec/modules/mytargetBidAdapter_spec.js diff --git a/modules/mytargetBidAdapter.js b/modules/mytargetBidAdapter.js new file mode 100644 index 00000000000..f55f2e6b802 --- /dev/null +++ b/modules/mytargetBidAdapter.js @@ -0,0 +1,112 @@ +import { _map } from '../src/utils.js'; +import { config } from '../src/config.js'; +import { registerBidder } from '../src/adapters/bidderFactory.js'; + +const BIDDER_CODE = 'mytarget'; +const BIDDER_URL = '//ad.mail.ru/hbid_prebid/'; +const DEFAULT_CURRENCY = 'RUB'; +const DEFAULT_TTL = 180; + +function buildPlacement(bidRequest) { + let { bidId, params } = bidRequest; + let { placementId, position, response, bidfloor } = params; + let placement = { + placementId, + id: bidId, + position: position || 0, + response: response || 0 + }; + + if (typeof bidfloor !== 'undefined') { + placement.bidfloor = bidfloor; + } + + return placement; +} + +function getSiteName(referrer) { + let sitename = config.getConfig('mytarget.sitename'); + + if (!sitename) { + const parsed = document.createElement('a'); + parsed.href = decodeURIComponent(referrer); + sitename = parsed.hostname; + } + + return sitename; +} + +function generateRandomId() { + return Math.random().toString(16).substring(2); +} + +export const spec = { + code: BIDDER_CODE, + + isBidRequestValid: function(bid) { + return !!bid.params.placementId; + }, + + buildRequests: function(validBidRequests, bidderRequest) { + let referrer = ''; + + if (bidderRequest && bidderRequest.refererInfo) { + referrer = bidderRequest.refererInfo.referer; + } + + const payload = { + places: _map(validBidRequests, buildPlacement), + site: { + sitename: getSiteName(referrer), + page: referrer + }, + settings: { + currency: DEFAULT_CURRENCY, + windowSize: { + width: window.screen.width, + height: window.screen.height + } + } + }; + + return { + method: 'POST', + url: BIDDER_URL, + data: payload, + }; + }, + + interpretResponse: function(serverResponse, bidRequest) { + let { body } = serverResponse; + + if (body.bids) { + return _map(body.bids, (bid) => { + let bidResponse = { + requestId: bid.id, + cpm: bid.price, + width: bid.size.width, + height: bid.size.height, + ttl: bid.ttl || DEFAULT_TTL, + currency: bid.currency || DEFAULT_CURRENCY, + creativeId: bid.creativeId || generateRandomId(), + netRevenue: true, + meta: { + advertiserDomains: bid.adomain && bid.adomain.length > 0 ? bid.adomain : [], + } + } + + if (bid.adm) { + bidResponse.ad = bid.adm; + } else { + bidResponse.adUrl = bid.displayUrl; + } + + return bidResponse; + }); + } + + return []; + } +} + +registerBidder(spec); diff --git a/test/spec/modules/mytargetBidAdapter_spec.js b/test/spec/modules/mytargetBidAdapter_spec.js new file mode 100644 index 00000000000..62d139bb926 --- /dev/null +++ b/test/spec/modules/mytargetBidAdapter_spec.js @@ -0,0 +1,199 @@ +import { expect } from 'chai'; +import { spec } from 'modules/mytargetBidAdapter'; + +describe('MyTarget Adapter', function() { + describe('isBidRequestValid', function () { + it('should return true when required params found', function () { + let validBid = { + bidder: 'mytarget', + params: { + placementId: '1' + } + }; + + expect(spec.isBidRequestValid(validBid)).to.equal(true); + }); + + it('should return false for when required params are not passed', function () { + let invalidBid = { + bidder: 'mytarget', + params: {} + }; + + expect(spec.isBidRequestValid(invalidBid)).to.equal(false); + }); + }); + + describe('buildRequests', function () { + let bidRequests = [ + { + bidId: 'bid1', + bidder: 'mytarget', + params: { + placementId: '1' + } + }, + { + bidId: 'bid2', + bidder: 'mytarget', + params: { + placementId: '2', + position: 1, + response: 1, + bidfloor: 10000 + } + } + ]; + let bidderRequest = { + refererInfo: { + referer: 'https://example.com?param=value' + } + }; + + let bidRequest = spec.buildRequests(bidRequests, bidderRequest); + + it('should build single POST request for multiple bids', function() { + expect(bidRequest.method).to.equal('POST'); + expect(bidRequest.url).to.equal('//ad.mail.ru/hbid_prebid/'); + expect(bidRequest.data).to.be.an('object'); + expect(bidRequest.data.places).to.be.an('array'); + expect(bidRequest.data.places).to.have.lengthOf(2); + }); + + it('should pass bid parameters', function() { + let place1 = bidRequest.data.places[0]; + let place2 = bidRequest.data.places[1]; + + expect(place1.placementId).to.equal('1'); + expect(place2.placementId).to.equal('2'); + expect(place1.id).to.equal('bid1'); + expect(place2.id).to.equal('bid2'); + }); + + it('should pass default position and response type', function() { + let place = bidRequest.data.places[0]; + + expect(place.position).to.equal(0); + expect(place.response).to.equal(0); + }); + + it('should pass provided position and response type', function() { + let place = bidRequest.data.places[1]; + + expect(place.position).to.equal(1); + expect(place.response).to.equal(1); + }); + + it('should not pass default bidfloor', function() { + let place = bidRequest.data.places[0]; + + expect(place.bidfloor).not.to.exist; + }); + + it('should not pass provided bidfloor', function() { + let place = bidRequest.data.places[1]; + + expect(place.bidfloor).to.exist; + expect(place.bidfloor).to.equal(10000); + }); + + it('should pass site parameters', function() { + let site = bidRequest.data.site; + + expect(site).to.be.an('object'); + expect(site.sitename).to.equal('example.com'); + expect(site.page).to.equal('https://example.com?param=value'); + }); + + it('should pass settings', function() { + let settings = bidRequest.data.settings; + + expect(settings).to.be.an('object'); + expect(settings.currency).to.equal('RUB'); + expect(settings.windowSize).to.be.an('object'); + expect(settings.windowSize.width).to.equal(window.screen.width); + expect(settings.windowSize.height).to.equal(window.screen.height); + }); + }); + + describe('interpretResponse', function () { + let serverResponse = { + body: { + 'bidder_status': + [ + { + 'bidder': 'mail.ru', + 'response_time_ms': 100, + 'num_bids': 2 + } + ], + 'bids': + [ + { + 'displayUrl': 'https://ad.mail.ru/hbid_imp/12345', + 'size': + { + 'height': '400', + 'width': '240' + }, + 'id': '1', + 'currency': 'RUB', + 'price': 100, + 'ttl': 360, + 'creativeId': '123456' + }, + { + 'adm': '

Ad

', + 'size': + { + 'height': '250', + 'width': '300' + }, + 'id': '2', + 'price': 200 + } + ] + } + }; + + let bids = spec.interpretResponse(serverResponse); + + it('should return empty array for response with no bids', function() { + let emptyBids = spec.interpretResponse({ body: {} }); + + expect(emptyBids).to.have.lengthOf(0); + }); + + it('should parse all bids from response', function() { + expect(bids).to.have.lengthOf(2); + }); + + it('should parse bid with ad url', function() { + expect(bids[0].requestId).to.equal('1'); + expect(bids[0].cpm).to.equal(100); + expect(bids[0].width).to.equal('240'); + expect(bids[0].height).to.equal('400'); + expect(bids[0].ttl).to.equal(360); + expect(bids[0].currency).to.equal('RUB'); + expect(bids[0]).to.have.property('creativeId'); + expect(bids[0].creativeId).to.equal('123456'); + expect(bids[0].netRevenue).to.equal(true); + expect(bids[0].adUrl).to.equal('https://ad.mail.ru/hbid_imp/12345'); + expect(bids[0]).to.not.have.property('ad'); + }); + + it('should parse bid with ad markup', function() { + expect(bids[1].requestId).to.equal('2'); + expect(bids[1].cpm).to.equal(200); + expect(bids[1].width).to.equal('300'); + expect(bids[1].height).to.equal('250'); + expect(bids[1].ttl).to.equal(180); + expect(bids[1].currency).to.equal('RUB'); + expect(bids[1]).to.have.property('creativeId'); + expect(bids[1].creativeId).not.to.equal('123456'); + expect(bids[1].netRevenue).to.equal(true); + expect(bids[1].ad).to.equal('

Ad

'); + expect(bids[1]).to.not.have.property('adUrl'); + }); + }); +}); From 80bc6e2b85bbbc57fb2d626375c6b88de8c92c3a Mon Sep 17 00:00:00 2001 From: Renato Aguilar <41385245+raguilar-ias@users.noreply.github.com> Date: Thu, 30 Sep 2021 17:21:29 -0500 Subject: [PATCH 63/84] IAS RTD adapter: improve workflow (#7431) --- modules/iasRtdProvider.js | 150 +++++++++++++---------- test/spec/modules/iasRtdProvider_spec.js | 77 +++++++++++- 2 files changed, 154 insertions(+), 73 deletions(-) diff --git a/modules/iasRtdProvider.js b/modules/iasRtdProvider.js index 25ca39c23d6..6f7b2d5215d 100644 --- a/modules/iasRtdProvider.js +++ b/modules/iasRtdProvider.js @@ -1,13 +1,18 @@ -import { isArray, getAdUnitSizes, getKeys, logError } from '../src/utils.js'; import { submodule } from '../src/hook.js'; +import * as utils from '../src/utils.js'; +import { ajax } from '../src/ajax.js'; import { getGlobal } from '../src/prebidGlobal.js'; -import { ajaxBuilder } from '../src/ajax.js'; /** @type {string} */ const MODULE_NAME = 'realTimeData'; const SUBMODULE_NAME = 'ias'; - -let bidResponses = {}; +const IAS_HOST = 'https://pixel.adsafeprotected.com/services/pub'; +export let iasTargeting = {}; +const BRAND_SAFETY_OBJECT_FIELD_NAME = 'brandSafety'; +const FRAUD_FIELD_NAME = 'fr'; +const SLOTS_OBJECT_FIELD_NAME = 'slots'; +const CUSTOM_FIELD_NAME = 'custom'; +const IAS_KW = 'ias-kw'; /** * Module init @@ -16,12 +21,17 @@ let bidResponses = {}; * @return {boolean} */ export function init(config, userConsent) { + const params = config.params; + if (!params || !params.pubId) { + utils.logError('missing pubId param for IAS provider'); + return false; + } return true; } function stringifySlotSizes(sizes) { let result = ''; - if (isArray(sizes)) { + if (utils.isArray(sizes)) { result = sizes.reduce((acc, size) => { acc.push(size.join('.')); return acc; @@ -31,13 +41,14 @@ function stringifySlotSizes(sizes) { return result; } -function stringifySlot(bidRequest, adUnitPath) { - const sizes = getAdUnitSizes(bidRequest); +function stringifySlot(bidRequest) { + const sizes = utils.getAdUnitSizes(bidRequest); const id = bidRequest.code; const ss = stringifySlotSizes(sizes); - const p = bidRequest.code; + const adSlot = utils.getGptSlotInfoForAdUnitCode(bidRequest.code); + const p = utils.isEmpty(adSlot) ? bidRequest.code : adSlot.gptSlot; const slot = { id, ss, p }; - const keyValues = getKeys(slot).map(function (key) { + const keyValues = utils.getKeys(slot).map(function (key) { return [key, slot[key]].join(':'); }); return '{' + keyValues.join(',') + '}'; @@ -51,35 +62,29 @@ function stringifyScreenSize() { return [(window.screen && window.screen.width) || -1, (window.screen && window.screen.height) || -1].join('.'); } -function getPageLevelKeywords(response) { +function formatTargetingData(adUnit) { let result = {}; - if (response.brandSafety) { - shallowMerge(result, response.brandSafety); + if (iasTargeting[BRAND_SAFETY_OBJECT_FIELD_NAME]) { + utils.mergeDeep(result, iasTargeting[BRAND_SAFETY_OBJECT_FIELD_NAME]); + } + if (iasTargeting[FRAUD_FIELD_NAME]) { + result[FRAUD_FIELD_NAME] = iasTargeting[FRAUD_FIELD_NAME]; + } + if (iasTargeting[CUSTOM_FIELD_NAME] && IAS_KW in iasTargeting[CUSTOM_FIELD_NAME]) { + result[IAS_KW] = iasTargeting[CUSTOM_FIELD_NAME][IAS_KW]; + } + if (iasTargeting[SLOTS_OBJECT_FIELD_NAME] && adUnit in iasTargeting[SLOTS_OBJECT_FIELD_NAME]) { + utils.mergeDeep(result, iasTargeting[SLOTS_OBJECT_FIELD_NAME][adUnit]); } - result.fr = response.fr; - result.custom = response.custom; return result; } -function shallowMerge(dest, src) { - getKeys(src).reduce((dest, srcKey) => { - dest[srcKey] = src[srcKey]; - return dest; - }, dest); -} - -function getBidRequestData(reqBidsConfigObj, callback, config) { - const adUnits = reqBidsConfigObj.adUnits || getGlobal().adUnits; - let isFinish = false; - - const IAS_HOST = 'https://pixel.adsafeprotected.com/services/pub'; - const { pubId, adUnitPath } = config.params; - const anId = pubId; +function constructQueryString(anId, adUnits) { let queries = []; queries.push(['anId', anId]); queries = queries.concat(adUnits.reduce(function (acc, request) { - acc.push(['slot', stringifySlot(request, adUnitPath)]); + acc.push(['slot', stringifySlot(request)]); return acc; }, [])); @@ -87,58 +92,69 @@ function getBidRequestData(reqBidsConfigObj, callback, config) { queries.push(['sr', stringifyScreenSize()]); queries.push(['url', encodeURIComponent(window.location.href)]); - const queryString = encodeURI(queries.map(qs => qs.join('=')).join('&')); - - const ajax = ajaxBuilder(); - - ajax(`${IAS_HOST}?${queryString}`, { - success: function (response, request) { - if (!isFinish) { - if (request.status === 200) { - const iasResponse = JSON.parse(response); - const commonBidResponse = {}; - shallowMerge(commonBidResponse, getPageLevelKeywords(iasResponse)); - commonBidResponse.slots = iasResponse.slots; - bidResponses = commonBidResponse; - adUnits.forEach(adUnit => { - adUnit.bids.forEach(bid => { - const rtd = bid.rtd || {}; - const iasRtd = {}; - iasRtd[SUBMODULE_NAME] = Object.assign({}, rtd[SUBMODULE_NAME], bidResponses); - bid.rtd = Object.assign({}, rtd, iasRtd); - }); - }); - } - isFinish = true; - } - callback(); - }, - error: function () { - logError('failed to retrieve targeting information'); - callback(); - } - }); + return encodeURI(queries.map(qs => qs.join('=')).join('&')); +} + +function parseResponse(result) { + let iasResponse = {}; + try { + iasResponse = JSON.parse(result); + } catch (err) { + utils.logError('error', err); + } + iasTargeting = iasResponse; } function getTargetingData(adUnits, config, userConsent) { const targeting = {}; - Object.keys(bidResponses).forEach(key => bidResponses[key] === undefined ? delete bidResponses[key] : {}); try { - adUnits.forEach(function(adUnit) { - targeting[adUnit] = bidResponses; - }); + if (!utils.isEmpty(iasTargeting)) { + adUnits.forEach(function (adUnit) { + targeting[adUnit] = formatTargetingData(adUnit); + }); + } } catch (err) { - logError('error', err); + utils.logError('error', err); } + utils.logInfo('IAS targeting', targeting); return targeting; } +export function getApiCallback() { + return { + success: function (response, req) { + if (req.status === 200) { + try { + parseResponse(response); + } catch (e) { + utils.logError('Unable to parse IAS response.', e); + } + } + }, + error: function () { + utils.logError('failed to retrieve IAS data'); + } + } +} + +function getBidRequestData(reqBidsConfigObj, callback, config, userConsent) { + const adUnits = reqBidsConfigObj.adUnits || getGlobal().adUnits; + const { pubId } = config.params; + const queryString = constructQueryString(pubId, adUnits); + ajax( + `${IAS_HOST}?${queryString}`, + getApiCallback(), + undefined, + { method: 'GET' } + ); +} + /** @type {RtdSubmodule} */ export const iasSubModule = { name: SUBMODULE_NAME, init: init, - getBidRequestData: getBidRequestData, - getTargetingData: getTargetingData + getTargetingData: getTargetingData, + getBidRequestData: getBidRequestData }; submodule(MODULE_NAME, iasSubModule); diff --git a/test/spec/modules/iasRtdProvider_spec.js b/test/spec/modules/iasRtdProvider_spec.js index e5e12355566..192b2c6e3c3 100644 --- a/test/spec/modules/iasRtdProvider_spec.js +++ b/test/spec/modules/iasRtdProvider_spec.js @@ -1,7 +1,9 @@ -import { iasSubModule } from 'modules/iasRtdProvider.js'; +import { iasSubModule, iasTargeting } from 'modules/iasRtdProvider.js'; import { expect } from 'chai'; import { server } from 'test/mocks/xhr.js'; +const responseHeader = { 'Content-Type': 'application/json' }; + describe('iasRtdProvider is a RTD provider that', function () { it('has the correct module name', function () { expect(iasSubModule.name).to.equal('ias'); @@ -10,8 +12,33 @@ describe('iasRtdProvider is a RTD provider that', function () { it('exists', function () { expect(iasSubModule.init).to.be.a('function'); }); - it('returns true', function () { - expect(iasSubModule.init()).to.equal(true); + it('returns false missing config params', function () { + const config = { + name: 'ias', + waitForIt: true, + }; + const value = iasSubModule.init(config); + expect(value).to.equal(false); + }); + it('returns false missing pubId param', function () { + const config = { + name: 'ias', + waitForIt: true, + params: {} + }; + const value = iasSubModule.init(config); + expect(value).to.equal(false); + }); + it('returns false missing pubId param', function () { + const config = { + name: 'ias', + waitForIt: true, + params: { + pubId: '123456' + } + }; + const value = iasSubModule.init(config); + expect(value).to.equal(true); }); }); describe('has a method `getBidRequestData` that', function () { @@ -30,10 +57,17 @@ describe('iasRtdProvider is a RTD provider that', function () { const adUnitsOriginal = adUnits; iasSubModule.getBidRequestData({ adUnits: adUnits }, callback, config); request = server.requests[0]; - server.respond(); + request.respond(200, responseHeader, JSON.stringify(data)); expect(request.url).to.be.include(`https://pixel.adsafeprotected.com/services/pub?anId=1234`); expect(adUnits).to.length(2); expect(adUnits[0]).to.be.eq(adUnitsOriginal[0]); + const targetingKeys = Object.keys(iasTargeting); + const dataKeys = Object.keys(data); + expect(targetingKeys.length).to.equal(dataKeys.length); + expect(targetingKeys['fr']).to.be.eq(dataKeys['fr']); + expect(targetingKeys['brandSafety']).to.be.eq(dataKeys['brandSafety']); + expect(targetingKeys['ias-kw']).to.be.eq(dataKeys['ias-kw']); + expect(targetingKeys['slots']).to.be.eq(dataKeys['slots']); }); }); @@ -42,10 +76,32 @@ describe('iasRtdProvider is a RTD provider that', function () { expect(iasSubModule.getTargetingData).to.be.a('function'); }); it('invoke method', function () { - const targeting = iasSubModule.getTargetingData(adUnits, config); - expect(adUnits).to.length(2); + const targeting = iasSubModule.getTargetingData(adUnitsCode, config); + expect(adUnitsCode).to.length(2); expect(targeting).to.be.not.null; expect(targeting).to.be.not.empty; + expect(targeting['one-div-id']).to.be.not.null; + const targetingKeys = Object.keys(targeting['one-div-id']); + expect(targetingKeys.length).to.equal(10); + expect(targetingKeys['adt']).to.be.not.null; + expect(targetingKeys['alc']).to.be.not.null; + expect(targetingKeys['dlm']).to.be.not.null; + expect(targetingKeys['drg']).to.be.not.null; + expect(targetingKeys['hat']).to.be.not.null; + expect(targetingKeys['off']).to.be.not.null; + expect(targetingKeys['vio']).to.be.not.null; + expect(targetingKeys['fr']).to.be.not.null; + expect(targetingKeys['ias-kw']).to.be.not.null; + expect(targetingKeys['id']).to.be.not.null; + expect(targeting['one-div-id']['adt']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['alc']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['dlm']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['drg']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['hat']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['off']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['vio']).to.be.eq('veryLow'); + expect(targeting['one-div-id']['fr']).to.be.eq('false'); + expect(targeting['one-div-id']['id']).to.be.eq('4813f7a2-1f22-11ec-9bfd-0a1107f94461'); }); }); }); @@ -58,6 +114,8 @@ const config = { } }; +const adUnitsCode = ['one-div-id', 'two-div-id']; + const adUnits = [ { code: 'one-div-id', @@ -87,3 +145,10 @@ const adUnits = [ } }] }]; + +const data = { + brandSafety: { adt: 'veryLow', alc: 'veryLow', dlm: 'veryLow', drg: 'veryLow', hat: 'veryLow', off: 'veryLow', vio: 'veryLow' }, + custom: { 'ias-kw': ['IAS_5995_KW', 'IAS_7066_KW', 'IAS_7232_KW', 'IAS_7364_KW', 'IAS_3894_KW', 'IAS_6535_KW', 'IAS_6153_KW', 'IAS_5238_KW', 'IAS_7393_KW', 'IAS_1499_KW', 'IAS_7376_KW', 'IAS_1035_KW', 'IAS_6566_KW', 'IAS_1058_KW', 'IAS_11338_724_KW', 'IAS_7301_KW', 'IAS_15969_725_KW', 'IAS_6358_KW', 'IAS_710_KW', 'IAS_5445_KW', 'IAS_3822_KW', 'IAS_4901_KW', 'IAS_5806_KW', 'IAS_460_KW', 'IAS_11461_702_KW', 'IAS_5681_KW', 'IAS_17609_1240_KW', 'IAS_6634_KW', 'IAS_5597_KW'] }, + fr: 'false', + slots: { 'one-div-id': { id: '4813f7a2-1f22-11ec-9bfd-0a1107f94461' } } +}; From 68b21beb67d9f36c46adb0df4bebf7fc810014a7 Mon Sep 17 00:00:00 2001 From: MK Platform <88486298+mediakeys-platform@users.noreply.github.com> Date: Fri, 1 Oct 2021 16:07:52 +0200 Subject: [PATCH 64/84] Mediakeys bid adapter: native and video support (#7452) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Mediatypes native and video support * fix utils reference * add isNumber & isInteger to imports * fix typo in isNumber * Ensure instream tracking sends bidWon event * Use production endpoint Co-authored-by: François Maturel Co-authored-by: Chris Huie --- modules/mediakeysBidAdapter.js | 418 +++++++++++++++- modules/mediakeysBidAdapter.md | 108 +++++ test/spec/modules/mediakeysBidAdapter_spec.js | 457 ++++++++++++++++-- 3 files changed, 918 insertions(+), 65 deletions(-) diff --git a/modules/mediakeysBidAdapter.js b/modules/mediakeysBidAdapter.js index 5b48e732942..ea0ce897395 100644 --- a/modules/mediakeysBidAdapter.js +++ b/modules/mediakeysBidAdapter.js @@ -1,4 +1,5 @@ -import { getWindowTop, isFn, logWarn, getDNT, deepAccess, isArray, inIframe, mergeDeep, isStr, isEmpty, deepSetValue, deepClone, parseUrl, cleanObj, logError, triggerPixel } from '../src/utils.js'; +import find from 'core-js-pure/features/array/find.js'; +import { getWindowTop, isFn, logWarn, getDNT, deepAccess, isArray, inIframe, mergeDeep, isStr, isEmpty, deepSetValue, deepClone, parseUrl, cleanObj, logError, triggerPixel, isInteger, isNumber } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; @@ -8,10 +9,63 @@ const AUCTION_TYPE = 1; const BIDDER_CODE = 'mediakeys'; const ENDPOINT = 'https://prebid.eu-central-1.bidder.mediakeys.io/bids'; const GVLID = 498; -const SUPPORTED_MEDIA_TYPES = [BANNER]; +const SUPPORTED_MEDIA_TYPES = [BANNER, NATIVE, VIDEO]; const DEFAULT_CURRENCY = 'USD'; const NET_REVENUE = true; +const NATIVE_ASSETS_MAPPING = [ + { name: 'title', id: 1, type: 0 }, + { name: 'image', id: 2, type: 3 }, + { name: 'icon', id: 3, type: 1 }, + { name: 'sponsoredBy', id: 5, type: 1 }, + { name: 'body', id: 6, type: 2 }, + { name: 'rating', id: 7, type: 3 }, + { name: 'likes', id: 8, type: 4 }, + { name: 'downloads', id: 9, type: 5 }, + { name: 'price', id: 10, type: 6 }, + { name: 'salePrice', id: 11, type: 7 }, + { name: 'phone', id: 12, type: 8 }, + { name: 'address', id: 13, type: 9 }, + { name: 'body2', id: 14, type: 10 }, + { name: 'displayUrl', id: 15, type: 11 }, + { name: 'cta', id: 16, type: 12 }, +]; + +// This provide a whitelist and a basic validation of OpenRTB native 1.2 options. +// https://www.iab.com/wp-content/uploads/2018/03/OpenRTB-Native-Ads-Specification-Final-1.2.pdf +const ORTB_NATIVE_PARAMS = { + context: value => [1, 2, 3].indexOf(value) !== -1, + plcmttype: value => [1, 2, 3, 4].indexOf(value) !== -1 +}; + +// This provide a whitelist and a basic validation of OpenRTB 2.5 video options. +// https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-API-Specification-Version-2-5-FINAL.pdf +const ORTB_VIDEO_PARAMS = { + mimes: value => Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string'), + minduration: value => isInteger(value), + maxduration: value => isInteger(value), + protocols: value => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].indexOf(v) !== -1), + w: value => isInteger(value), + h: value => isInteger(value), + startdelay: value => isInteger(value), + placement: value => [1, 2, 3, 4, 5].indexOf(value) !== -1, + linearity: value => [1, 2].indexOf(value) !== -1, + skip: value => [0, 1].indexOf(value) !== -1, + skipmin: value => isInteger(value), + skipafter: value => isInteger(value), + sequence: value => isInteger(value), + battr: value => Array.isArray(value) && value.every(v => Array.from({length: 17}, (_, i) => i + 1).indexOf(v) !== -1), + maxextended: value => isInteger(value), + minbitrate: value => isInteger(value), + maxbitrate: value => isInteger(value), + boxingallowed: value => [0, 1].indexOf(value) !== -1, + playbackmethod: value => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5, 6].indexOf(v) !== -1), + playbackend: value => [1, 2, 3].indexOf(value) !== -1, + delivery: value => [1, 2, 3].indexOf(value) !== -1, + pos: value => [0, 1, 2, 3, 4, 5, 6, 7].indexOf(value) !== -1, + api: value => Array.isArray(value) && value.every(v => [1, 2, 3, 4, 5, 6].indexOf(v) !== -1), +}; + /** * Detects the capability to reach window.top. * @@ -83,6 +137,33 @@ function getFloor(bid, mediaType, size = '*') { return (!isNaN(floor.floor) && floor.currency === DEFAULT_CURRENCY) ? floor.floor : false } +/** + * Returns the highest floor price found when a bid have + * several mediaTypes. + * + * @param {*} bid a Prebid.js bid (request) object + * @returns {number|boolean} + */ +function getHighestFloor(bid) { + const floors = []; + + for (let mediaType in bid.mediaTypes) { + const floor = getFloor(bid, mediaType); + + if (isNumber(floor)) { + floors.push(floor); + } + } + + if (!floors.length) { + return false; + } + + return floors.reduce((a, b) => { + return Math.max(a, b); + }); +} + /** * Returns an openRTB 2.5 object. * This one will be populated at each step of the buildRequest process. @@ -153,6 +234,190 @@ function createBannerImp(bid) { } } +/** + * Returns an openRtb 2.5 native object with a native 1.2 request. + * + * @param {object} bid Prebid bid object from request + * @returns {object} + */ +function createNativeImp(bid) { + if (!bid.nativeParams) { + logWarn(`${BIDDER_CODE}: bid.nativeParams object has not been found.`); + return + } + + const nativeParams = deepClone(bid.nativeParams); + + const nativeAdUnitParams = deepAccess(bid, 'mediaTypes.native', {}); + const nativeBidderParams = deepAccess(bid, 'params.native', {}); + + const extraParams = { + ...nativeAdUnitParams, + ...nativeBidderParams + }; + + const nativeObject = { + ver: '1.2', + context: 1, // overwrited later if needed + plcmttype: 1, // overwrited later if needed + assets: [] + } + + Object.keys(ORTB_NATIVE_PARAMS).forEach(name => { + if (extraParams.hasOwnProperty(name)) { + if (ORTB_NATIVE_PARAMS[name](extraParams[name])) { + nativeObject[name] = extraParams[name]; + } else { + logWarn(`${BIDDER_CODE}: the OpenRTB native param ${name} has been skipped due to misformating. Please refer to OpenRTB Native spec.`); + } + } + }); + + // just a helper function + const setImageAssetSizes = function(asset, param) { + if (param.sizes && param.sizes.length) { + asset.img.w = param.sizes ? param.sizes[0] : undefined; + asset.img.h = param.sizes ? param.sizes[1] : undefined; + } + + if (!asset.img.w) { + asset.img.wmin = 0; + } + + if (!asset.img.h) { + asset.img.hmin = 0; + } + } + + // Prebid.js "image" type support. + // Add some defaults to support special type provided by Prebid.js `mediaTypes.native.type: "image"` + const nativeImageType = deepAccess(bid, 'mediaTypes.native.type'); + if (nativeImageType === 'image') { + // Default value is ones of the recommended by the spec: https://www.iab.com/wp-content/uploads/2018/03/OpenRTB-Native-Ads-Specification-Final-1.2.pdf + nativeParams.title.len = 90; + } + + for (let key in nativeParams) { + if (nativeParams.hasOwnProperty(key)) { + const internalNativeAsset = find(NATIVE_ASSETS_MAPPING, ref => ref.name === key); + if (!internalNativeAsset) { + logWarn(`${BIDDER_CODE}: the asset "${key}" has not been found in Prebid assets map. Skipped for request.`); + continue; + } + + const param = nativeParams[key]; + + const asset = { + id: internalNativeAsset.id, + required: param.required ? 1 : 0 + } + + switch (key) { + case 'title': + if (param.len || param.length) { + asset.title = { + len: param.len || param.length, + ext: param.ext + } + } else { + logWarn(`${BIDDER_CODE}: "title.length" property for native asset is required. Skipped for request.`) + continue; + } + break; + + case 'image': + asset.img = { + type: internalNativeAsset.type, + mimes: param.mimes, + ext: param.ext, + } + + setImageAssetSizes(asset, param); + + break; + case 'icon': + asset.img = { + type: internalNativeAsset.type, + mimes: param.mimes, + ext: param.ext, + } + + setImageAssetSizes(asset, param); + break; + + case 'sponsoredBy': // sponsored + case 'body': // desc + case 'rating': + case 'likes': + case 'downloads': + case 'price': + case 'salePrice': + case 'phone': + case 'address': + case 'body2': // desc2 + case 'displayUrl': + case 'cta': + // generic asset.data + asset.data = { + type: internalNativeAsset.type, + len: param.len, + ext: param.ext + } + break; + } + + nativeObject.assets.push(asset); + } + } + + if (nativeObject.assets.length) { + return { + request: nativeObject + } + } +} + +/** + * Returns an openRtb 2.5 video object. + * + * @param {object} bid Prebid bid object from request + * @returns {object} + */ +function createVideoImp(bid) { + const videoAdUnitParams = deepAccess(bid, 'mediaTypes.video', {}); + const videoBidderParams = deepAccess(bid, 'params.video', {}); + const computedParams = {}; + + // Special case for playerSize. + // Eeach props will be overrided if they are defined in config. + if (Array.isArray(videoAdUnitParams.playerSize)) { + const tempSize = (Array.isArray(videoAdUnitParams.playerSize[0])) ? videoAdUnitParams.playerSize[0] : videoAdUnitParams.playerSize; + computedParams.w = tempSize[0]; + computedParams.h = tempSize[1]; + } + + const videoParams = { + ...computedParams, + ...videoAdUnitParams, + ...videoBidderParams + }; + + const video = {}; + + // Only whitelisted OpenRTB options need to be validated. + Object.keys(ORTB_VIDEO_PARAMS).forEach(name => { + if (videoParams.hasOwnProperty(name)) { + if (ORTB_VIDEO_PARAMS[name](videoParams[name])) { + video[name] = videoParams[name]; + } else { + logWarn(`${BIDDER_CODE}: the OpenRTB video param ${name} has been skipped due to misformating. Please refer to OpenRTB 2.5 spec.`); + } + } + }); + + return video +} + /** * Create the OpenRTB 2.5 imp object. * @@ -167,20 +432,34 @@ function createImp(bid) { secure: 1, }; + // There is no default floor. bidfloor is set only + // if the priceFloors module is activated and returns a valid floor. + const floor = getHighestFloor(bid); + if (isNumber(floor)) { + imp.bidfloor = floor; + } + // Only supports proper mediaTypes definition… for (let mediaType in bid.mediaTypes) { - // There is no default floor. bidfloor is set only - // if the priceFloors module is activated and returns a valid floor. - const floor = getFloor(bid, mediaType); - if (floor) { - imp.bidfloor = floor; - } - - if (mediaType === BANNER) { - const banner = createBannerImp(bid); - if (banner) { - imp.banner = banner; - } + switch (mediaType) { + case BANNER: + const banner = createBannerImp(bid); + if (banner) { + imp.banner = banner; + } + break; + case NATIVE: + const native = createNativeImp(bid); + if (native) { + imp.native = native; + } + break; + case VIDEO: + const video = createVideoImp(bid); + if (video) { + imp.video = video; + } + break; } } @@ -213,6 +492,94 @@ function getPrimaryCatFromResponse(cat) { } } +/** + * Create the Prebid.js native object from response. + * + * @param {*} bid bid object from response + * @returns {object} Prebid.js native object used in response + */ +function nativeBidResponseHandler(bid) { + const nativeAdm = JSON.parse(bid.adm); + if (!nativeAdm || !nativeAdm.assets.length) { + logError(`${BIDDER_CODE}: invalid native response.`); + return; + } + + const native = {} + + nativeAdm.assets.forEach(asset => { + if (asset.title) { + native.title = asset.title.text; + return; + } + + if (asset.img) { + switch (asset.img.type) { + case 1: + native.icon = { + url: asset.img.url, + width: asset.img.w, + height: asset.img.h + }; + break; + default: + native.image = { + url: asset.img.url, + width: asset.img.w, + height: asset.img.h + }; + break; + } + return; + } + + if (asset.data) { + const internalNativeAsset = find(NATIVE_ASSETS_MAPPING, ref => ref.id === asset.id); + if (internalNativeAsset) { + native[internalNativeAsset.name] = asset.data.value; + } + } + }); + + if (nativeAdm.link) { + if (nativeAdm.link.url) { + native.clickUrl = nativeAdm.link.url; + } + if (Array.isArray(nativeAdm.link.clicktrackers)) { + native.clickTrackers = nativeAdm.link.clicktrackers + } + } + + if (Array.isArray(nativeAdm.eventtrackers)) { + native.impressionTrackers = []; + nativeAdm.eventtrackers.forEach(tracker => { + // Only Impression events are supported. Prebid does not support Viewability events yet. + if (tracker.event !== 1) { + return; + } + + // methods: + // 1: image + // 2: js + // note: javascriptTrackers is a string. If there's more than one JS tracker in bid response, the last script will be used. + switch (tracker.method) { + case 1: + native.impressionTrackers.push(tracker.url); + break; + case 2: + native.javascriptTrackers = ``; + break; + } + }); + } + + if (nativeAdm.privacy) { + native.privacyLink = nativeAdm.privacy; + } + + return native; +} + export const spec = { code: BIDDER_CODE, @@ -355,6 +722,29 @@ export const spec = { meta: cleanObj(meta) }; + if (mediaType === NATIVE) { + const native = nativeBidResponseHandler(bid); + if (native) { + newBid.native = native; + } + } + + if (mediaType === VIDEO) { + // Note: + // Mediakeys bid adapter expects a publisher has set his own video player + // in the `mediaTypes.video` configuration object. + + // Mediakeys bidder does not provide inline XML in the bid response + // newBid.vastXml = bid.ext.vast_url; + + // For instream video, disable server cache as vast is generated per bid request + newBid.videoCacheKey = 'no_cache'; + + // The vast URL is server independently and must be fetched before video rendering in the renderer + // appending '&no_cache' is safe and fast as the vast url always have parameters + newBid.vastUrl = bid.ext.vast_url + '&no_cache'; + } + bidResponses.push(newBid); }); }); diff --git a/modules/mediakeysBidAdapter.md b/modules/mediakeysBidAdapter.md index 75e69659c8a..ec313c2fe3a 100644 --- a/modules/mediakeysBidAdapter.md +++ b/modules/mediakeysBidAdapter.md @@ -29,3 +29,111 @@ var adUnits = [ }] }, ``` + +## Native only Ad Unit + +The Mediakeys adapter accepts two optional params for native requests. Please see the [OpenRTB Native Ads Specification](https://www.iab.com/wp-content/uploads/2018/03/OpenRTB-Native-Ads-Specification-Final-1.2.pdf) for valid values. + +``` +var adUnits = [ +{ + code: 'test', + mediaTypes: { + native: { + type: 'image', + } + }, + bids: [{ + bidder: 'mediakeys', + params: { + native: { + context: 1, // ORTB Native Context Type IDs. Default `1`. + plcmttype: 1, // ORTB Native Placement Type IDs. Default `1`. + } + } + }] +}, +``` + +## Video only Ad Unit + +The Mediakeys adapter accepts any valid openRTB 2.5 video property. Properties can be defined at the adUnit `mediaTypes.video` or `bid[].params` level. + +### Outstream context + +``` +var adUnits = [ +{ + code: 'test', + mediaTypes: { + video: { + context: 'outstream', + playerSize: [300, 250], + // additional OpenRTB video params + // placement: 2, + // api: [1], + // … + } + }, + renderer: { + url: 'https://acdn.adnxs.com/video/outstream/ANOutstreamVideo.js', + render: function (bid) { + var bidReqConfig = pbjs.adUnits.find(bidReq => bidReq.bidId === bid.impid); + + if (bidReqConfig && bidReqConfig.mediaTypes && bidReqConfig.mediaTypes.video && bidReqConfig.mediaTypes.video.context === 'outstream') { + var adResponse = fetch(bid.vastUrl).then(resp => resp.text()).then(text => ({ + ad: { + video: { + content: text, + player_width: bid.width || bidReqConfig.mediaTypes.video.playerSize[0], + player_height: bid.height || bidReqConfig.mediaTypes.video.playerSize[1], + } + } + })) + + adResponse.then((ad) => { + bid.renderer.push(() => { + ANOutstreamVideo.renderAd({ + targetId: bid.adUnitCode, + adResponse: ad + }); + }); + }) + } + } + }, + bids: [{ + bidder: 'mediakeys', + params: { + video: { + // additional OpenRTB video params. Will be merged with params defined at mediaTypes level + } + } + }] +}, +``` + +### Instream context + +``` +var adUnits = [ +{ + code: 'test', + mediaTypes: { + video: { + context: 'instream', + playerSize: [300, 250], + // additional OpenRTB video params + // placement: 2, + // api: [1], + // … + } + }, + bids: [{ + bidder: 'mediakeys', + params: { + // additional OpenRTB video params. Will be merged with params defined at mediaTypes level + } + }] +}, +``` diff --git a/test/spec/modules/mediakeysBidAdapter_spec.js b/test/spec/modules/mediakeysBidAdapter_spec.js index 040c0abd566..602524e6eb3 100644 --- a/test/spec/modules/mediakeysBidAdapter_spec.js +++ b/test/spec/modules/mediakeysBidAdapter_spec.js @@ -1,9 +1,11 @@ import { expect } from 'chai'; +import find from 'core-js-pure/features/array/find.js'; import { spec } from 'modules/mediakeysBidAdapter.js'; import { newBidder } from 'src/adapters/bidderFactory.js'; import * as utils from 'src/utils.js'; import { config } from 'src/config.js'; import { BANNER, NATIVE, VIDEO } from '../../../src/mediaTypes.js'; +import { OUTSTREAM } from '../../../src/video.js'; describe('mediakeysBidAdapter', function () { const adapter = newBidder(spec); @@ -39,39 +41,100 @@ describe('mediakeysBidAdapter', function () { } }; + const bidNative = { + bidder: 'mediakeys', + params: {}, + mediaTypes: { + native: { + body: { + required: true + }, + title: { + required: true, + len: 800 + }, + sponsoredBy: { + required: true + }, + body2: { + required: true + }, + image: { + required: true, + sizes: [[300, 250], [300, 600], [100, 150]], + }, + icon: { + required: true, + sizes: [50, 50], + }, + }, + }, + nativeParams: { + body: { + required: true + }, + title: { + required: true, + len: 800 + }, + sponsoredBy: { + required: true + }, + body2: { + required: true + }, + image: { + required: true, + sizes: [[300, 250], [300, 600], [100, 150]], + }, + icon: { + required: true, + sizes: [50, 50], + }, + }, + adUnitCode: 'div-gpt-ad-1460505748561-0', + transactionId: '47789656-9e5c-4250-b7e0-2ce4cbe71a55', + bidId: '299320f4de980d', + bidderRequestId: '1c1b642f803242', + auctionId: '84212956-c377-40e8-b000-9885a06dc692', + src: 'client', + bidRequestsCount: 1, + bidderRequestsCount: 1, + bidderWinsCount: 0, + ortb2Imp: { + ext: { data: { something: 'test' } } + } + }; + + const bidVideo = { + bidder: 'mediakeys', + params: {}, + mediaTypes: { + video: { + context: OUTSTREAM, + playerSize: [480, 320] + } + }, + adUnitCode: 'div-gpt-ad-1460505748561-0', + transactionId: '47789656-9e5c-4250-b7e0-2ce4cbe71a55', + bidId: '299320f4de980d', + bidderRequestId: '1c1b642f803242', + auctionId: '84212956-c377-40e8-b000-9885a06dc692', + src: 'client', + bidRequestsCount: 1, + bidderRequestsCount: 1, + bidderWinsCount: 0, + ortb2Imp: { + ext: { data: { something: 'test' } } + } + }; + const bidderRequest = { bidderCode: 'mediakeys', auctionId: '84212956-c377-40e8-b000-9885a06dc692', bidderRequestId: '1c1b642f803242', bids: [ - { - bidder: 'mediakeys', - params: {}, - mediaTypes: { - banner: { - sizes: [ - [300, 250], - [300, 600], - ], - }, - }, - adUnitCode: 'div-gpt-ad-1460505748561-0', - transactionId: '47789656-9e5c-4250-b7e0-2ce4cbe71a55', - sizes: [ - [300, 250], - [300, 600], - ], - bidId: '299320f4de980d', - bidderRequestId: '1c1b642f803242', - auctionId: '84212956-c377-40e8-b000-9885a06dc692', - src: 'client', - bidRequestsCount: 1, - bidderRequestsCount: 1, - bidderWinsCount: 0, - ortb2Imp: { - ext: { data: { something: 'test' } } - } - }, + bid ], auctionStart: 1620973766319, timeout: 1000, @@ -116,23 +179,25 @@ describe('mediakeysBidAdapter', function () { it('should create imp for supported mediaType only', function() { const bidRequests = [utils.deepClone(bid)]; const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; bidRequests[0].mediaTypes.video = { playerSize: [300, 250], - context: 'outstream' + context: OUTSTREAM } - bidRequests[0].mediaTypes.native = { - type: 'image' - } + bidRequests[0].mediaTypes.native = bidNative.mediaTypes.native; + bidRequests[0].nativeParams = bidNative.mediaTypes.native; + + bidderRequestCopy.bids = bidRequests[0]; const request = spec.buildRequests(bidRequests, bidderRequestCopy); const data = request.data; expect(data.imp.length).to.equal(1); expect(data.imp[0].banner).to.exist; - expect(data.imp[0].video).to.not.exist; - expect(data.imp[0].native).to.not.exist; + expect(data.imp[0].video).to.exist; + expect(data.imp[0].native).to.exist; }); it('should get expected properties with default values (no params set)', function () { @@ -161,6 +226,205 @@ describe('mediakeysBidAdapter', function () { expect(data.imp[0].ext.data.something).to.equal('test'); }); + describe('native imp', function() { + it('should get a native object in request', function() { + const bidRequests = [utils.deepClone(bidNative)]; + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].native).to.exist; + expect(data.imp[0].native.request.ver).to.equal('1.2'); + expect(data.imp[0].native.request.context).to.equal(1); + expect(data.imp[0].native.request.plcmttype).to.equal(1); + expect(data.imp[0].native.request.assets.length).to.equal(6); + // find the asset body + const bodyAsset = find(data.imp[0].native.request.assets, asset => asset.id === 6); + expect(bodyAsset.data.type).to.equal(2); + }); + + it('should get a native object in request with properties filled with params values', function() { + const bidRequests = [utils.deepClone(bidNative)]; + bidRequests[0].params = { + native: { + context: 3, + plcmttype: 3, + } + } + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].native).to.exist; + expect(data.imp[0].native.request.ver).to.equal('1.2'); + expect(data.imp[0].native.request.context).to.equal(3); + expect(data.imp[0].native.request.plcmttype).to.equal(3); + expect(data.imp[0].native.request.assets.length).to.equal(6); + }); + + it('should get a native object in request when native type ,image" has been set', function() { + const bidRequests = [utils.deepClone(bidNative)]; + bidRequests[0].mediaTypes.native = { type: 'image' }; + bidRequests[0].nativeParams = { + image: { required: true }, + title: { required: true }, + sponsoredBy: { required: true }, + clickUrl: { required: true }, // [1] Will be ignored as it is used in response validation only + body: { required: false }, + icon: { required: false }, + }; + + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].native).to.exist; + expect(data.imp[0].native.request.ver).to.equal('1.2'); + expect(data.imp[0].native.request.context).to.equal(1); + expect(data.imp[0].native.request.plcmttype).to.equal(1); + expect(data.imp[0].native.request.assets.length).to.equal(5); // [1] clickUrl ignored + }); + + it('should log errors and ignore misformated assets', function() { + const bidRequests = [utils.deepClone(bidNative)]; + delete bidRequests[0].nativeParams.title.len; + bidRequests[0].nativeParams.unregistred = {required: true}; + + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + utilsMock.expects('logWarn').twice(); + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].native).to.exist; + expect(data.imp[0].native.request.assets.length).to.equal(5); + }); + }); + + describe('video imp', function() { + it('should get a video object in request', function() { + const bidRequests = [utils.deepClone(bidVideo)]; + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].banner).to.not.exist; + expect(data.imp[0].video).to.exist; + expect(data.imp[0].video.w).to.equal(480); + expect(data.imp[0].video.h).to.equal(320); + }); + + it('should ignore and warn misformated ORTB video properties', function() { + const bidRequests = [utils.deepClone(bidVideo)]; + bidRequests[0].mediaTypes.video.unknown = 'foo'; + bidRequests[0].mediaTypes.video.placement = 10; + bidRequests[0].mediaTypes.video.skipmin = 5; + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].banner).to.not.exist; + expect(data.imp[0].video).to.exist; + expect(data.imp[0].video.w).to.equal(480); + expect(data.imp[0].video.h).to.equal(320); + expect(data.imp[0].video.skipmin).to.equal(5); + expect(data.imp[0].video.placement).to.not.exist; + expect(data.imp[0].video.unknown).to.not.exist; + }); + + it('should merge adUnit mediaTypes level and bidder level params properties ', function() { + const bidRequests = [utils.deepClone(bidVideo)]; + bidRequests[0].mediaTypes.video.placement = 1; + bidRequests[0].mediaTypes.video.mimes = ['video/mpeg4']; + bidRequests[0].mediaTypes.video.protocols = [1]; + bidRequests[0].mediaTypes.video.minduration = 10; + bidRequests[0].mediaTypes.video.maxduration = 45; + bidRequests[0].mediaTypes.video.skipmin = 5; + bidRequests[0].mediaTypes.video.sequence = 3; + bidRequests[0].mediaTypes.video.linearity = 1; + bidRequests[0].mediaTypes.video.battr = [12]; + bidRequests[0].mediaTypes.video.maxextended = 10; + bidRequests[0].mediaTypes.video.minbitrate = 720; + bidRequests[0].mediaTypes.video.maxbitrate = 720; + bidRequests[0].mediaTypes.video.boxingallowed = 1; + bidRequests[0].mediaTypes.video.playbackmethod = [1]; + bidRequests[0].mediaTypes.video.playbackend = 2; + bidRequests[0].mediaTypes.video.delivery = 2; + bidRequests[0].mediaTypes.video.pos = 0; + bidRequests[0].mediaTypes.video.companionad = [{ w: 360, h: 80 }] + bidRequests[0].mediaTypes.video.api = [1]; + bidRequests[0].mediaTypes.video.companiontype = [1]; + + // bidder level + bidRequests[0].params.video = { + pos: 2, // override + skip: 1, + skipafter: 10, + startdelay: 3 + }; + + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + utilsMock.expects('logWarn').never(); + + const request = spec.buildRequests(bidRequests, bidderRequestCopy); + const data = request.data; + + expect(data.imp.length).to.equal(1); + expect(data.imp[0].id).to.equal(bidRequests[0].bidId); + expect(data.imp[0].banner).to.not.exist; + expect(data.imp[0].video).to.exist; + + expect(Object.keys(data.imp[0].video).length).to.equal(23); // 21 ortb params (2 skipped) + computed width/height. + expect(data.imp[0].video.w).to.equal(480); + expect(data.imp[0].video.h).to.equal(320); + expect(data.imp[0].video.mimes[0]).to.equal('video/mpeg4'); + expect(data.imp[0].video.pos).to.equal(2); + expect(data.imp[0].video.skip).to.equal(1); + expect(data.imp[0].video.skipafter).to.equal(10); + expect(data.imp[0].video.startdelay).to.equal(3); + expect(data.imp[0].video.companionad).to.not.exist; + expect(data.imp[0].video.companiontype).to.not.exist; + }); + + it('should log warn message when OpenRTB validation fails ', function() { + const bidRequests = [utils.deepClone(bidVideo)]; + bidRequests[0].mediaTypes.video.placement = 'string'; + bidRequests[0].mediaTypes.video.api = 1; + const bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + utilsMock.expects('logWarn').twice(); + + spec.buildRequests(bidRequests, bidderRequestCopy); + }); + }); + it('should get expected properties with values from params', function () { const bidRequests = [utils.deepClone(bid)]; bidRequests[0].params = { @@ -265,13 +529,25 @@ describe('mediakeysBidAdapter', function () { expect(data.imp[0].bidfloor).to.not.exist; }); - it('should get and set floor by mediatype', function() { + it('should get the highest floorPrice found when bid have several mediaTypes', function() { const bidWithPriceFloors = utils.deepClone(bid); bidWithPriceFloors.mediaTypes.video = { playerSize: [600, 480] }; + bidWithPriceFloors.mediaTypes.native = { + body: { + required: true + } + }; + + bidWithPriceFloors.nativeParams = { + body: { + required: true + } + }; + bidWithPriceFloors.getFloor = getFloorTest; const bidRequests = [bidWithPriceFloors]; @@ -279,10 +555,9 @@ describe('mediakeysBidAdapter', function () { const data = request.data; expect(data.imp[0].banner).to.exist; - expect(data.imp[0].bidfloor).to.equal(1); - - // expect(data.imp[1].video).to.exist; - // expect(data.imp[1].bidfloor).to.equal(5); + expect(data.imp[0].video).to.exist; + expect(data.imp[0].native).to.exist; + expect(data.imp[0].bidfloor).to.equal(5); }); it('should set properties at payload level from FPD', function() { @@ -420,8 +695,8 @@ describe('mediakeysBidAdapter', function () { const bidRequests = [utils.deepClone(bid)]; const request = spec.buildRequests(bidRequests, bidderRequest); sinon.stub(utils, 'isArray').throws(); - spec.interpretResponse(rawServerResponse, request); utilsMock.expects('logError').once(); + spec.interpretResponse(rawServerResponse, request); utils.isArray.restore(); }); @@ -483,28 +758,108 @@ describe('mediakeysBidAdapter', function () { }); }); - it('Build video response', function () { - const bidRequests = [utils.deepClone(bid)]; + it('interprets video bid response', function () { + const vastUrl = 'https://url.local?req=content'; + const bidRequests = [utils.deepClone(bidVideo)]; const request = spec.buildRequests(bidRequests, bidderRequest); + const rawServerResponseVideo = utils.deepClone(rawServerResponse); rawServerResponseVideo.body.seatbid[0].bid[0].ext.prebid.type = 'V'; + rawServerResponseVideo.body.seatbid[0].bid[0].ext.vast_url = vastUrl; + const response = spec.interpretResponse(rawServerResponseVideo, request); expect(response.length).to.equal(1); expect(response[0].mediaType).to.equal('video'); expect(response[0].meta.mediaType).to.equal('video'); + expect(response[0].vastXml).to.not.exist; + expect(response[0].vastUrl).to.equal(vastUrl + '&no_cache'); + expect(response[0].videoCacheKey).to.equal('no_cache'); }); - it('Build native response', function () { - const bidRequests = [utils.deepClone(bid)]; - const request = spec.buildRequests(bidRequests, bidderRequest); - const rawServerResponseVideo = utils.deepClone(rawServerResponse); - rawServerResponseVideo.body.seatbid[0].bid[0].ext.prebid.type = 'N'; - const response = spec.interpretResponse(rawServerResponseVideo, request); + describe('Native response', function () { + let bidRequests; + let bidderRequestCopy; + let request; + let rawServerResponseNative; + let nativeObject; + + beforeEach(function() { + bidRequests = [utils.deepClone(bidNative)]; + bidderRequestCopy = utils.deepClone(bidderRequest); + bidderRequestCopy.bids = bidRequests; + + request = spec.buildRequests(bidRequests, bidderRequestCopy); + + nativeObject = { + ver: '1.2', + privacy: 'https://privacy.me', + assets: [ + { id: 5, data: { type: 1, value: 'Sponsor Brand' } }, + { id: 6, data: { type: 2, value: 'Brand Body' } }, + { id: 14, data: { type: 10, value: 'Brand Body 2' } }, + { id: 1, title: { text: 'Brand Title' } }, + { id: 2, img: { type: 3, url: 'https://url.com/img.jpg', w: 300, h: 250 } }, + { id: 3, img: { type: 1, url: 'https://url.com/ico.png', w: 50, h: 50 } }, + ], + link: { + url: 'https://brand.me', + clicktrackers: [ + 'https://click.me' + ] + }, + eventtrackers: [ + { event: 1, method: 1, url: 'https://click.me' }, + { event: 1, method: 2, url: 'https://click-script.me' } + ] + }; - expect(response.length).to.equal(1); - expect(response[0].mediaType).to.equal('native'); - expect(response[0].meta.mediaType).to.equal('native'); + rawServerResponseNative = utils.deepClone(rawServerResponse); + rawServerResponseNative.body.seatbid[0].bid[0].ext.prebid.type = 'N'; + rawServerResponseNative.body.seatbid[0].bid[0].adm = JSON.stringify(nativeObject) + }); + + it('should ignore invalid native response', function() { + const nativeObjectCopy = utils.deepClone(nativeObject); + nativeObjectCopy.assets = []; + const rawServerResponseNativeCopy = utils.deepClone(rawServerResponseNative); + rawServerResponseNativeCopy.body.seatbid[0].bid[0].adm = JSON.stringify(nativeObjectCopy) + const response = spec.interpretResponse(rawServerResponseNativeCopy, request); + expect(response.length).to.equal(1); + expect(response[0].native).to.not.exist; + }); + + it('should build a classic Prebid.js native object for response', function() { + const rawServerResponseNativeCopy = utils.deepClone(rawServerResponseNative); + const response = spec.interpretResponse(rawServerResponseNativeCopy, request); + expect(response.length).to.equal(1); + expect(response[0].mediaType).to.equal('native'); + expect(response[0].meta.mediaType).to.equal('native'); + expect(response[0].native).to.exist; + expect(response[0].native.body).to.exist; + expect(response[0].native.privacyLink).to.exist; + expect(response[0].native.body2).to.exist; + expect(response[0].native.sponsoredBy).to.exist; + expect(response[0].native.image).to.exist; + expect(response[0].native.icon).to.exist; + expect(response[0].native.title).to.exist; + expect(response[0].native.clickUrl).to.exist; + expect(response[0].native.clickTrackers).to.exist; + expect(response[0].native.clickTrackers.length).to.equal(1); + expect(response[0].native.javascriptTrackers).to.equal(''); + expect(response[0].native.impressionTrackers).to.exist; + expect(response[0].native.impressionTrackers.length).to.equal(1); + }); + + it('should ignore eventtrackers with a unsupported type', function() { + const rawServerResponseNativeCopy = utils.deepClone(rawServerResponseNative); + const nativeObjectCopy = utils.deepClone(nativeObject); + nativeObjectCopy.eventtrackers[0].event = 2; + rawServerResponseNativeCopy.body.seatbid[0].bid[0].adm = JSON.stringify(nativeObjectCopy); + const response = spec.interpretResponse(rawServerResponseNativeCopy, request); + expect(response[0].native.impressionTrackers).to.exist; + expect(response[0].native.impressionTrackers.length).to.equal(0); + }) }); }); From 35c1db85bcdb7c892c4e7530d145b88d0b90e37f Mon Sep 17 00:00:00 2001 From: Stephen Johnston Date: Fri, 1 Oct 2021 12:09:53 -0400 Subject: [PATCH 65/84] Prebid Core: Support for Devcontainer for VSCode, Docker Desktop, Codespaces, etc. (#7487) * support common ports, add chrome headless for testing * change Dockefile variant to match passed in variant initially --- .devcontainer/Dockerfile | 11 +++++++++++ .devcontainer/devcontainer.json | 27 +++++++++++++++++++++++++++ .devcontainer/postCreate.sh | 6 ++++++ 3 files changed, 44 insertions(+) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/postCreate.sh diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 00000000000..cfb29ebdfa9 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,11 @@ +ARG VARIANT="12" +FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:${VARIANT} + +# [Optional] Uncomment this section to install additional OS packages. +# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ +# && apt-get -y install --no-install-recommends + +RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - +RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list +RUN apt update +RUN apt install -y google-chrome-stable xvfb diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000000..0176b8317b3 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,27 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: +// https://github.com/microsoft/vscode-dev-containers/tree/main/containers/javascript-node +{ + "name": "Ubuntu", + + "build": { + "dockerfile": "Dockerfile", + "args": { "VARIANT": "12" } + }, + + "postCreateCommand": "bash .devcontainer/postCreate.sh", + + // Set *default* container specific settings.json values on container create. + "settings": {}, + + + // Add the IDs of extensions you want installed when the container is created. + "extensions": [ + "nickdodd79.gulptasks" + ], + + // 9999 is web server, 9876 is karma + "forwardPorts": [9876, 9999], + + // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. + "remoteUser": "node" +} diff --git a/.devcontainer/postCreate.sh b/.devcontainer/postCreate.sh new file mode 100644 index 00000000000..7e14a2d200d --- /dev/null +++ b/.devcontainer/postCreate.sh @@ -0,0 +1,6 @@ +echo "Post Create Starting" + +nvm install +nvm use +npm install gulp-cli -g +npm ci From c6e74d2848136701ef286da4298d45dfdb143494 Mon Sep 17 00:00:00 2001 From: mamatic <52153441+mamatic@users.noreply.github.com> Date: Mon, 4 Oct 2021 10:58:30 +0200 Subject: [PATCH 66/84] Ats Analytics Adapter: handle preflight request error & increase _lr_sample_rate cookie expiration (#7462) * ATS-analytics-adapter - increase sampling rate cookie expiration time, handle error on preflight request * ATS-analytics-adapter - increase adapter version to 2 * ATS-analytics-adapter - fix logs * ATS-analytics-adapter - add unit tests * ATS-analytics-adapter - code improvements, add more unit tests --- modules/atsAnalyticsAdapter.js | 45 ++++++++++--------- test/spec/modules/atsAnalyticsAdapter_spec.js | 39 +++++++++++++++- 2 files changed, 62 insertions(+), 22 deletions(-) diff --git a/modules/atsAnalyticsAdapter.js b/modules/atsAnalyticsAdapter.js index df293556a4c..d1e520b4b8f 100644 --- a/modules/atsAnalyticsAdapter.js +++ b/modules/atsAnalyticsAdapter.js @@ -13,9 +13,6 @@ export const storage = getStorageManager(); */ const analyticsType = 'endpoint'; -// dev endpoints -// const preflightUrl = 'https://analytics-check.publishersite.xyz/check/'; -// export const analyticsUrl = 'https://analyticsv2.publishersite.xyz'; const preflightUrl = 'https://check.analytics.rlcdn.com/check/'; export const analyticsUrl = 'https://analytics.rlcdn.com'; @@ -23,7 +20,7 @@ export const analyticsUrl = 'https://analytics.rlcdn.com'; let handlerRequest = []; let handlerResponse = []; -let atsAnalyticsAdapterVersion = 1; +let atsAnalyticsAdapterVersion = 2; let browsersList = [ /* Googlebot */ @@ -207,12 +204,6 @@ let browsersList = [ }, ]; -function setSamplingCookie(samplRate) { - let now = new Date(); - now.setTime(now.getTime() + 3600000); - storage.setCookie('_lr_sampling_rate', samplRate, now.toUTCString()); -} - let listOfSupportedBrowsers = ['Safari', 'Chrome', 'Firefox', 'Microsoft Edge']; function bidRequestedHandler(args) { @@ -276,16 +267,23 @@ function sendDataToAnalytic () { // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { logInfo('ATS Analytics - preflight request!'); - ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { - let samplingRateObject = JSON.parse(data); - logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); - let samplingRate = samplingRateObject['samplingRate']; - setSamplingCookie(samplingRate); - let samplingRateNumber = Number(samplingRate); - if (data && samplingRate && atsAnalyticsAdapter.shouldFireRequest(samplingRateNumber) && envelopeSourceCookieValue != null) { - sendDataToAnalytic(); - } - }, undefined, { method: 'GET', crossOrigin: true }); + ajax(preflightUrl + atsAnalyticsAdapter.context.pid, + { + success: function (data) { + let samplingRateObject = JSON.parse(data); + logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); + let samplingRate = samplingRateObject.samplingRate; + atsAnalyticsAdapter.setSamplingCookie(samplingRate); + let samplingRateNumber = Number(samplingRate); + if (data && samplingRate && atsAnalyticsAdapter.shouldFireRequest(samplingRateNumber) && envelopeSourceCookieValue != null) { + sendDataToAnalytic(); + } + }, + error: function () { + atsAnalyticsAdapter.setSamplingCookie(0); + logInfo('ATS Analytics - Sampling Rate Request Error!'); + } + }, undefined, {method: 'GET', crossOrigin: true}); } function callHandler(evtype, args) { @@ -356,6 +354,13 @@ atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { atsAnalyticsAdapter.getUserAgent = function () { return window.navigator.userAgent; }; + +atsAnalyticsAdapter.setSamplingCookie = function (samplRate) { + const now = new Date(); + now.setTime(now.getTime() + 86400000); + storage.setCookie('_lr_sampling_rate', samplRate, now.toUTCString()); +} + // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { diff --git a/test/spec/modules/atsAnalyticsAdapter_spec.js b/test/spec/modules/atsAnalyticsAdapter_spec.js index e2dd4747199..7f662ffd06d 100644 --- a/test/spec/modules/atsAnalyticsAdapter_spec.js +++ b/test/spec/modules/atsAnalyticsAdapter_spec.js @@ -5,16 +5,18 @@ import {server} from '../../mocks/xhr.js'; import {parseBrowser} from '../../../modules/atsAnalyticsAdapter.js'; import {getStorageManager} from '../../../src/storageManager.js'; import {analyticsUrl} from '../../../modules/atsAnalyticsAdapter.js'; +let utils = require('src/utils'); let events = require('src/events'); let constants = require('src/constants.json'); export const storage = getStorageManager(); - +let sandbox; describe('ats analytics adapter', function () { beforeEach(function () { sinon.stub(events, 'getEvents').returns([]); storage.setCookie('_lr_env_src_ats', 'true', 'Thu, 01 Jan 1970 00:00:01 GMT'); + sandbox = sinon.sandbox.create(); }); afterEach(function () { @@ -22,6 +24,7 @@ describe('ats analytics adapter', function () { atsAnalyticsAdapter.getUserAgent.restore(); atsAnalyticsAdapter.disableAnalytics(); Math.random.restore(); + sandbox.restore(); }); describe('track', function () { @@ -87,7 +90,7 @@ describe('ats analytics adapter', function () { let expectedAfterBid = { 'Data': [{ 'has_envelope': true, - 'adapter_version': 1, + 'adapter_version': 2, 'bidder': 'appnexus', 'bid_id': '30c77d079cdf17', 'auction_id': 'a5b849e5-87d7-4205-8300-d063084fcfb7', @@ -185,6 +188,12 @@ describe('ats analytics adapter', function () { let browser = parseBrowser(); expect(browser).to.equal('Firefox'); }) + it('check browser is unknown', function () { + sinon.stub(atsAnalyticsAdapter, 'getUserAgent').returns(undefined); + sinon.stub(Math, 'random').returns(0.99); + let browser = parseBrowser(); + expect(browser).to.equal('Unknown'); + }) it('should not fire analytics request if sampling rate is 0', function () { sinon.stub(atsAnalyticsAdapter, 'getUserAgent').returns('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25'); sinon.stub(Math, 'random').returns(0.99); @@ -205,5 +214,31 @@ describe('ats analytics adapter', function () { let result = atsAnalyticsAdapter.shouldFireRequest(10); expect(result).to.equal(false); }) + + it('should set cookie value to 10 for _lr_sampling_rate', function () { + sinon.stub(atsAnalyticsAdapter, 'getUserAgent').returns('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25'); + sinon.stub(Math, 'random').returns(0.99); + atsAnalyticsAdapter.setSamplingCookie(10); + let samplingRate = storage.getCookie('_lr_sampling_rate'); + expect(samplingRate).to.equal('10'); + }) + + it('should set cookie value to 0 for _lr_sampling_rate', function () { + sinon.stub(atsAnalyticsAdapter, 'getUserAgent').returns('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25'); + sinon.stub(Math, 'random').returns(0.99); + atsAnalyticsAdapter.setSamplingCookie(0); + let samplingRate = storage.getCookie('_lr_sampling_rate'); + expect(samplingRate).to.equal('0'); + }) + + it('enable analytics', function () { + sandbox.stub(utils, 'logError'); + sinon.stub(atsAnalyticsAdapter, 'getUserAgent').returns('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25'); + sinon.stub(Math, 'random').returns(0.99); + atsAnalyticsAdapter.enableAnalytics({ + options: {} + }); + expect(utils.logError.called).to.equal(true); + }) }) }) From f62ad030f4927277149dfe183c35d37df84008ef Mon Sep 17 00:00:00 2001 From: Amanda Dillon <41923726+agdillon@users.noreply.github.com> Date: Mon, 4 Oct 2021 06:21:22 -0600 Subject: [PATCH 67/84] SpotX: add support for price floors module (#7481) --- modules/spotxBidAdapter.js | 16 +++++++++- test/spec/modules/spotxBidAdapter_spec.js | 36 +++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/modules/spotxBidAdapter.js b/modules/spotxBidAdapter.js index 7111aa7e7ce..7d5865684a7 100644 --- a/modules/spotxBidAdapter.js +++ b/modules/spotxBidAdapter.js @@ -1,4 +1,4 @@ -import { logError, deepAccess, isArray, getBidIdParameter, getDNT, deepSetValue, isEmpty, _each, logMessage, logWarn, isBoolean, isNumber, isPlainObject } from '../src/utils.js'; +import { logError, deepAccess, isArray, getBidIdParameter, getDNT, deepSetValue, isEmpty, _each, logMessage, logWarn, isBoolean, isNumber, isPlainObject, isFn } from '../src/utils.js'; import { config } from '../src/config.js'; import { Renderer } from '../src/Renderer.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; @@ -163,6 +163,20 @@ export const spec = { } }; + if (isFn(bid.getFloor)) { + let floorInfo = bid.getFloor({ + currency: 'USD', + mediaType: 'video', + size: '*' + }); + + if (floorInfo.currency === 'USD') { + spotxReq.bidfloor = floorInfo.floor; + } + } else if (getBidIdParameter('price_floor', bid.params) != '') { + spotxReq.bidfloor = getBidIdParameter('price_floor', bid.params); + } + if (getBidIdParameter('start_delay', bid.params) != '') { spotxReq.video.startdelay = 0 + Boolean(getBidIdParameter('start_delay', bid.params)); } diff --git a/test/spec/modules/spotxBidAdapter_spec.js b/test/spec/modules/spotxBidAdapter_spec.js index 2db8a1c9d2c..d536976092b 100644 --- a/test/spec/modules/spotxBidAdapter_spec.js +++ b/test/spec/modules/spotxBidAdapter_spec.js @@ -403,6 +403,42 @@ describe('the spotx adapter', function () { expect(request.data.ext.wrap_response).to.equal(0); config.getConfig.restore(); }); + + it('should pass price floor in USD from the floors module if available', function () { + var request; + + bid.getFloor = function () { + return { currency: 'USD', floor: 3 }; + } + + bid.params.price_floor = 2; + + request = spec.buildRequests([bid], bidRequestObj)[0]; + + expect(request.data.imp.bidfloor).to.equal(3); + }); + + it('should not pass price floor if price floors module gives a non-USD currency', function () { + var request; + + bid.getFloor = function () { + return { currency: 'EUR', floor: 3 }; + } + + request = spec.buildRequests([bid], bidRequestObj)[0]; + + expect(request.data.imp.bidfloor).to.be.undefined; + }); + + it('if floors module is not available, should pass price floor from price_floor param if available', function () { + var request; + + bid.params.price_floor = 2; + + request = spec.buildRequests([bid], bidRequestObj)[0]; + + expect(request.data.imp.bidfloor).to.equal(2); + }); }); describe('interpretResponse', function() { From 3d606dec8d7b0a4856a6a2c4e6bb58ae53beffea Mon Sep 17 00:00:00 2001 From: prebidtappx <77485538+prebidtappx@users.noreply.github.com> Date: Mon, 4 Oct 2021 18:41:15 +0200 Subject: [PATCH 68/84] tappxBidAdapter: fix wrong params (#7528) Co-authored-by: marc_tappx --- modules/tappxBidAdapter.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/modules/tappxBidAdapter.js b/modules/tappxBidAdapter.js index 337779d1d53..a026b2cd6a6 100644 --- a/modules/tappxBidAdapter.js +++ b/modules/tappxBidAdapter.js @@ -9,7 +9,7 @@ import { Renderer } from '../src/Renderer.js'; const BIDDER_CODE = 'tappx'; const TTL = 360; const CUR = 'USD'; -const TAPPX_BIDDER_VERSION = '0.1.0921'; +const TAPPX_BIDDER_VERSION = '0.1.1004'; const TYPE_CNN = 'prebidjs'; const LOG_PREFIX = '[TAPPX]: '; const VIDEO_SUPPORT = ['instream', 'outstream']; @@ -495,15 +495,16 @@ export function _getHostInfo(validBidRequests) { } function outstreamRender(bid, request) { + let rendererOptions = {}; + rendererOptions = (typeof bid.params[0].video != 'undefined') ? bid.params[0].video : {}; + rendererOptions.content = bid.vastXml; + bid.renderer.push(() => { window.tappxOutstream.renderAd({ sizes: [bid.width, bid.height], targetId: bid.adUnitCode, adResponse: bid.adResponse, - rendererOptions: { - content: bid.vastXml, - skip: (typeof bid.params[0].video.skip != 'undefined' && bid.params[0].video.skip > 0) ? bid.params[0].video.skip : 0 - } + rendererOptions: rendererOptions }); }); } From 20e0c44d9a2d5c14184536e2fce16f16eba0b4cf Mon Sep 17 00:00:00 2001 From: TheMediaGrid <44166371+TheMediaGrid@users.noreply.github.com> Date: Mon, 4 Oct 2021 20:21:06 +0300 Subject: [PATCH 69/84] TheMediaGridNM: Fix bug with wrong vastUrl (#7530) * Added TheMediaGridNM Bid Adapter * Updated required params for TheMediaGridNM Bid Adapter * Update TheMediGridNM Bid Adapter * Fix tests for TheMediaGridNM Bid Adapter * Fixes after review for TheMediaGridNM Bid Adapter * Add support of multi-format in TheMediaGrid Bid Adapter * Update sync url for grid and gridNM Bid Adapters * TheMediaGrid Bid Adapter: added keywords adUnit parameter * Update TheMediaGrid Bid Adapter to support keywords from config * Implement new request format for TheMediaGrid Bid Adapter * Fix jwpseg params for TheMediaGrid Bid Adapter * Update unit tests for The Media Grid Bid Adapter * Fix typo in TheMediaGrid Bid Adapter * Added test for jwTargeting in TheMediaGrid Bid Adapter * The new request format was made by default in TheMediaGrid Bid Adapter * Update userId format in ad request for TheMediaGrid Bid Adapter * Added bidFloor parameter for TheMediaGrid Bid Adapter * Fix for review TheMediaGrid Bid Adapter * Support floorModule in TheMediaGrid Bid Adapter * Fix empty bidfloor for TheMediaGrid Bid Adapter * Some change to restart autotests * Fix userIds format for TheMediaGrid Bid Adapter * Remove digitrust userId from TheMediaGrid Bid Adapter * Protocols was added in video section in ad request for TheMediaGrid Bid Adapter * TheMediaGrid: fix trouble with alias using * TheMediaGridNM: fix trouble with alias * TheMediaGrid Bid Adapter: added support of PBAdSlot module * TheMediaGrid Bid Adapter: fix typo * GridNM Bid Adapter: use absent in params data from mediaTypes * GridNM Bid Adapter: fix md file + add advertiserDomains support * TheMediaGrid and gridNM Bid Adapter: minor netRevenue fixes * gridNM Bid Adapter updates after review * TheMediaGrid Bid Adapter: fix keywords workflow * fix testing and kick off lgtm again * TheMediaGrid: added ext.bidder.grid.demandSource processing * TheMediaGrid: added user.id from fpd cookie * TheMediaGrid: control cookie setting via bidder config * TheMediaGrid: use localStorage instead cookie * TheMediaGridNM Bid Adapter: update adapter to use /hbjson endpoint * TheMediaGridNM: fix unnecessary conditions * TheMediaGrid: fix bug with nurl field in response * TheMediaGrid: update test * TheMediaGridNM: fix possible bug with nurl Co-authored-by: Chris Huie --- modules/gridNMBidAdapter.js | 13 +++---- test/spec/modules/gridNMBidAdapter_spec.js | 41 +++++++++++++++++++++- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/modules/gridNMBidAdapter.js b/modules/gridNMBidAdapter.js index 0daddb4ee42..3c46b25b8e1 100644 --- a/modules/gridNMBidAdapter.js +++ b/modules/gridNMBidAdapter.js @@ -231,7 +231,7 @@ export const spec = { if (!errorMessage && serverResponse.seatbid) { const serverBid = _getBidFromResponse(serverResponse.seatbid[0]); if (serverBid) { - if (!serverBid.adm) errorMessage = LOG_ERROR_MESS.noAdm + JSON.stringify(serverBid); + if (!serverBid.adm && !serverBid.nurl) errorMessage = LOG_ERROR_MESS.noAdm + JSON.stringify(serverBid); else if (!serverBid.price) errorMessage = LOG_ERROR_MESS.noPrice + JSON.stringify(serverBid); else if (serverBid.content_type !== 'video') errorMessage = LOG_ERROR_MESS.wrongContentType + serverBid.content_type; if (!errorMessage) { @@ -246,17 +246,18 @@ export const spec = { netRevenue: true, ttl: TIME_TO_LIVE, dealId: serverBid.dealid, - vastXml: serverBid.adm, mediaType: VIDEO, meta: { advertiserDomains: serverBid.adomain ? serverBid.adomain : [] - }, - adResponse: { - content: serverBid.adm } }; - if (serverBid.nurl) { + if (serverBid.adm) { + bidResponse.vastXml = serverBid.adm; + bidResponse.adResponse = { + content: bidResponse.vastXml + }; + } else if (serverBid.nurl) { bidResponse.vastUrl = serverBid.nurl; } diff --git a/test/spec/modules/gridNMBidAdapter_spec.js b/test/spec/modules/gridNMBidAdapter_spec.js index baff5862fca..89efe942c1f 100644 --- a/test/spec/modules/gridNMBidAdapter_spec.js +++ b/test/spec/modules/gridNMBidAdapter_spec.js @@ -341,6 +341,7 @@ describe('TheMediaGridNM Adapter', function () { const responses = [ {'bid': [{'price': 1.15, 'adm': '\n<\/Ad>\n<\/VAST>', 'content_type': 'video', 'h': 250, 'w': 300, 'dealid': 11}], 'seat': '2'}, {'bid': [{'price': 0.5, 'adm': '\n<\/Ad>\n<\/VAST>', 'content_type': 'video', 'h': 600, 'w': 300, adomain: ['my_domain.ru']}], 'seat': '2'}, + {'bid': [{'price': 2.00, 'nurl': 'https://some_test_vast_url.com', 'content_type': 'video', 'adomain': ['example.com'], 'w': 300, 'h': 600}], 'seat': '2'}, {'bid': [{'price': 0, 'h': 250, 'w': 300}], 'seat': '2'}, {'bid': [{'price': 0, 'adm': '\n<\/Ad>\n<\/VAST>', 'h': 250, 'w': 300}], 'seat': '2'}, undefined, @@ -394,6 +395,28 @@ describe('TheMediaGridNM Adapter', function () { 'context': 'instream' } } + }, + { + 'bidder': 'gridNM', + 'params': { + 'source': 'jwp', + 'secid': '11', + 'pubid': '22', + 'video': { + 'mimes': ['video/mp4'], + 'protocols': [1, 2, 3], + } + }, + 'adUnitCode': 'adunit-code-1', + 'sizes': [[300, 250], [300, 600]], + 'bidId': '127f4b12a432c', + 'bidderRequestId': 'a75bc868f32', + 'auctionId': '1cbd2feafe5e8b', + 'mediaTypes': { + 'video': { + 'context': 'instream' + } + } } ]; const requests = spec.buildRequests(bidRequests); @@ -435,6 +458,22 @@ describe('TheMediaGridNM Adapter', function () { 'adResponse': { 'content': '\n<\/Ad>\n<\/VAST>' } + }, + { + 'requestId': '127f4b12a432c', + 'cpm': 2.00, + 'creativeId': 'a75bc868f32', + 'dealId': undefined, + 'width': 300, + 'height': 600, + 'currency': 'USD', + 'mediaType': 'video', + 'netRevenue': true, + 'ttl': 360, + 'meta': { + advertiserDomains: ['example.com'] + }, + 'vastUrl': 'https://some_test_vast_url.com', } ]; @@ -445,7 +484,7 @@ describe('TheMediaGridNM Adapter', function () { }); it('handles wrong and nobid responses', function () { - responses.slice(2).forEach((resp) => { + responses.slice(3).forEach((resp) => { const request = spec.buildRequests([{ 'bidder': 'gridNM', 'params': { From d15d519850f90583668223db6a3166a3396e4f62 Mon Sep 17 00:00:00 2001 From: wojciech-bialy-wpm <67895844+wojciech-bialy-wpm@users.noreply.github.com> Date: Mon, 4 Oct 2021 19:58:23 +0200 Subject: [PATCH 70/84] sspBC Bid Adaptor : add native support, instream video support, & test coverage updates (#7447) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update tests for sspBC adapter Update tests for sspBC adapter: - change userSync test (due to tcf param appended in v4.6) - add tests for onBidWon and onTimeout * [sspbc-adapter] RC for 5.2 version of sspBCBidAdapter * [sspbc-adapter] RC for 5.2 version of sspBCBidAdapter(fixed commit) Co-authored-by: Wojciech Biały --- modules/sspBCBidAdapter.js | 219 ++++++++++++++++- modules/sspBCBidAdapter.md | 2 +- test/spec/modules/sspBCBidAdapter_spec.js | 272 +++++++++++++++++----- 3 files changed, 418 insertions(+), 75 deletions(-) diff --git a/modules/sspBCBidAdapter.js b/modules/sspBCBidAdapter.js index 44b96d42deb..188f41dfad9 100644 --- a/modules/sspBCBidAdapter.js +++ b/modules/sspBCBidAdapter.js @@ -1,7 +1,7 @@ import { isArray, deepAccess, logWarn, parseUrl } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; -import { BANNER } from '../src/mediaTypes.js'; +import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js'; import strIncludes from 'core-js-pure/features/string/includes.js'; const BIDDER_CODE = 'sspBC'; @@ -9,7 +9,7 @@ const BIDDER_URL = 'https://ssp.wp.pl/bidder/'; const SYNC_URL = 'https://ssp.wp.pl/bidder/usersync'; const NOTIFY_URL = 'https://ssp.wp.pl/bidder/notify'; const TMAX = 450; -const BIDDER_VERSION = '5.0'; +const BIDDER_VERSION = '5.2'; const W = window; const { navigator } = W; const oneCodeDetection = {}; @@ -155,6 +155,108 @@ const mapBanner = slot => { } } +/** + * @param {string} paramName Native parameter name + * @param {object} paramValue Native parameter value + * @returns {object} native asset object that conforms to ortb native ads spec + */ +const mapAsset = (paramName, paramValue) => { + let asset; + switch (paramName) { + case 'title': + asset = { + id: 0, + required: paramValue.required, + title: { len: paramValue.len } + } + break; + case 'cta': + asset = { + id: 1, + required: paramValue.required, + data: { type: 12 } + } + break; + case 'icon': + asset = { + id: 2, + required: paramValue.required, + img: { type: 1, w: paramValue.sizes[0], h: paramValue.sizes[1] } + } + break; + case 'image': + asset = { + id: 3, + required: paramValue.required, + img: { type: 3, w: paramValue.sizes[0], h: paramValue.sizes[1] } + } + break; + case 'body': + asset = { + id: 4, + required: paramValue.required, + data: { type: 2 } + } + break; + case 'sponsoredBy': + asset = { + id: 5, + required: paramValue.required, + data: { type: 1 } + } + break; + } + return asset; +} + +/** + * @param {object} slot Ad Unit Params by Prebid + * @returns {object} native object that conforms to ortb native ads spec + */ +const mapNative = slot => { + const native = utils.deepAccess(slot, 'mediaTypes.native'); + let assets; + if (native) { + const nativeParams = Object.keys(native); + assets = []; + nativeParams.forEach(par => { + const newAsset = mapAsset(par, native[par]); + if (newAsset) { assets.push(newAsset) }; + }); + } + return assets ? { request: JSON.stringify({ native: { assets } }) } : undefined; +} + +var mapVideo = slot => { + var video = utils.deepAccess(slot, 'mediaTypes.video'); + var videoParamsUsed = ['api', 'context', 'linearity', 'maxduration', 'mimes', 'protocols']; + var videoAssets; + + if (video) { + var videoParams = Object.keys(video); + var playerSize = video.playerSize; + videoAssets = {}; // player width / height + + if (playerSize) { + var maxSize = playerSize.reduce(function (prev, next) { + return next[0] >= prev[0] && next[1] >= prev[1] ? next : prev; + }, [1, 1]); + videoAssets.w = maxSize[0]; + videoAssets.h = maxSize[1]; + } // remaining supported params + + videoParams.forEach(function (par) { + if (videoParamsUsed.indexOf(par) >= 0) { + videoAssets[par] = video[par]; + } + + ; + }); + } + + return videoAssets; +}; + const mapImpression = slot => { const { adUnitCode, bidId, params = {}, ortb2Imp = {} } = slot; const { id, siteId } = params; @@ -165,32 +267,100 @@ const mapImpression = slot => { send this info as ext.pbsize */ const slotSize = slot.sizes.length ? slot.sizes.reduce((prev, next) => prev[0] * prev[1] <= next[0] * next[1] ? next : prev).join('x') : '1x1'; - adSizesCalled[slotSize] = adSizesCalled[slotSize] ? adSizesCalled[slotSize] + 1 : 1; + adSizesCalled[slotSize] = adSizesCalled[slotSize] ? adSizesCalled[slotSize] += 1 : 1; ext.data = Object.assign({ pbsize: `${slotSize}_${adSizesCalled[slotSize]}` }, ext.data); const imp = { id: id && siteId ? id : 'bidid-' + bidId, banner: mapBanner(slot), - // native: mapNative(slot), + native: mapNative(slot), + video: mapVideo(slot), tagid: adUnitCode, ext, }; // Check floorprices for this imp if (typeof slot.getFloor === 'function') { - let bannerFloor = 0; - // sspBC adapter accepts only floor per imp - check for maximum value for requested ad types and sizes + var bannerFloor = 0; + var nativeFloor = 0; + var videoFloor = 0; // sspBC adapter accepts only floor per imp - check for maximum value for requested ad types and sizes + if (slot.sizes.length) { - bannerFloor = slot.sizes.reduce((prev, next) => { - const currentFloor = slot.getFloor({ mediaType: 'banner', size: next }).floor; + bannerFloor = slot.sizes.reduce(function (prev, next) { + var currentFloor = slot.getFloor({ + mediaType: 'banner', + size: next + }).floor; return prev > currentFloor ? prev : currentFloor; }, 0); } - imp.bidfloor = bannerFloor; + + nativeFloor = slot.getFloor({ + mediaType: 'native' + }); + videoFloor = slot.getFloor({ + mediaType: 'video' + }); + imp.bidfloor = Math.max(bannerFloor, nativeFloor, videoFloor); } return imp; } +const isVideoAd = bid => { + const xmlTester = new RegExp(/^<\?xml/); + return bid.adm && bid.adm.match(xmlTester); +} + +const isNativeAd = bid => { + const xmlTester = new RegExp(/^{['"]native['"]/); + + return bid.adm && bid.adm.match(xmlTester); +} + +const parseNative = nativeData => { + const result = {}; + nativeData.assets.forEach(asset => { + const id = parseInt(asset.id); + switch (id) { + case 0: + result.title = asset.title.text; + break; + case 2: + result.icon = { + url: asset.img.url, + width: asset.img.w, + height: asset.img.h, + }; + break; + case 3: + result.image = { + url: asset.img.url, + width: asset.img.w, + height: asset.img.h, + }; + break; + case 4: + result.body = asset.data.value; + break; + case 5: + result.sponsoredBy = asset.data.value; + break; + + default: + utils.logWarn('Unrecognized native asset', asset); + } + }); + result.clickUrl = nativeData.link.url; + result.impressionTrackers = nativeData.imptrackers; + + if (utils.isArray(nativeData.jstracker)) { + result.javascriptTrackers = nativeData.jstracker; + } else if (nativeData.jstracker) { + result.javascriptTrackers = [nativeData.jstracker]; + } + return result; +} + const renderCreative = (site, auctionId, bid, seat, request) => { let gam; @@ -243,6 +413,7 @@ const renderCreative = (site, auctionId, bid, seat, request) => {