diff --git a/modules/ooloAnalyticsAdapter.js b/modules/ooloAnalyticsAdapter.js index 7195d6ac177..398459d604d 100644 --- a/modules/ooloAnalyticsAdapter.js +++ b/modules/ooloAnalyticsAdapter.js @@ -1,7 +1,7 @@ +import { _each, deepClone, pick, deepSetValue, getOrigin, logError, logInfo } 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 { config } from '../src/config.js' @@ -64,7 +64,7 @@ const onAuctionInit = (args) => { handleCustomFields(auction, AUCTION_INIT, args) - utils._each(adUnits, adUnit => { + _each(adUnits, adUnit => { auction.adUnits[adUnit.code] = { ...adUnit, auctionId, @@ -144,7 +144,7 @@ const onBidWon = (args) => { } const onBidTimeout = (args) => { - utils._each(args, bid => { + _each(args, bid => { const { auctionId, adUnitCode } = bid const bidId = parseBidId(bid) let bidCache = auctions[auctionId].adUnits[adUnitCode].bids[bidId] @@ -172,7 +172,7 @@ const onAuctionEnd = (args) => { } const onAdRenderFailed = (args) => { - const data = utils.deepClone(args) + const data = deepClone(args) data.timestamp = Date.now() if (data.bid) { @@ -232,7 +232,7 @@ function handleEvent(eventType, args) { } function sendEvent(eventType, args, isRaw) { - let data = utils.deepClone(args) + let data = deepClone(args) Object.assign(data, buildCommonDataProperties(), { eventType @@ -268,7 +268,7 @@ function checkEventsQueue() { } function buildAuctionData(auction) { - const auctionData = utils.deepClone(auction) + const auctionData = deepClone(auction) const keysToRemove = ['adUnitCodes', 'auctionStatus', 'bidderRequests', 'bidsReceived', 'noBids', 'winningBids', 'timestamp', 'config'] keysToRemove.forEach(key => { @@ -367,12 +367,12 @@ function handleCustomFields(obj, eventType, args) { const { pickFields, omitFields } = initOptions.serverConfig.events[eventType] if (pickFields && obj && args) { - Object.assign(obj, utils.pick(args, pickFields)) + Object.assign(obj, pick(args, pickFields)) } if (omitFields && obj && args) { omitFields.forEach(field => { - utils.deepSetValue(obj, field, undefined) + deepSetValue(obj, field, undefined) }) } } catch (e) { } @@ -382,7 +382,7 @@ function handleCustomRawFields(obj, omitRawFields) { try { if (omitRawFields && obj) { omitRawFields.forEach(field => { - utils.deepSetValue(obj, field, undefined) + deepSetValue(obj, field, undefined) }) } } catch (e) { } @@ -419,7 +419,7 @@ function sendPage() { screenHeight: window.screen.height, url: window.location.href, protocol: window.location.protocol, - origin: utils.getOrigin(), + origin: getOrigin(), referrer: getTopWindowReferrer(), pbVersion: prebidVersion, } @@ -507,7 +507,7 @@ ooloAdapter.enableAnalytics = function (config) { initOptions = config ? config.options : {} if (!initOptions.pid) { - utils.logError(buildLogMessage('enableAnalytics missing config object with "pid"')) + logError(buildLogMessage('enableAnalytics missing config object with "pid"')) return } @@ -520,9 +520,9 @@ ooloAdapter.enableAnalytics = function (config) { window.addEventListener('load', sendPage) } - utils.logInfo(buildLogMessage('enabled analytics adapter'), config) + logInfo(buildLogMessage('enabled analytics adapter'), config) ooloAdapter.enableAnalytics = function () { - utils.logInfo(buildLogMessage('Analytics adapter already enabled..')) + logInfo(buildLogMessage('Analytics adapter already enabled..')) } } diff --git a/modules/openwebBidAdapter.js b/modules/openwebBidAdapter.js index ef776ea81f5..9476d2d2914 100644 --- a/modules/openwebBidAdapter.js +++ b/modules/openwebBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { isNumber, deepAccess, isArray, 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'; @@ -14,7 +14,7 @@ export const spec = { gvlid: 280, supportedMediaTypes: [VIDEO, BANNER, ADPOD], isBidRequestValid: function (bid) { - return utils.isNumber(utils.deepAccess(bid, 'params.aid')); + return isNumber(deepAccess(bid, 'params.aid')); }, getUserSyncs: function (syncOptions, serverResponses) { const syncs = []; @@ -43,9 +43,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); }) @@ -82,26 +82,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) { @@ -126,26 +126,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'); } // end publisher env const bids = [] @@ -164,13 +164,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; @@ -178,9 +178,9 @@ function prepareBidRequests(bidReq) { bidReqParams.AdmType = 'iframe'; } 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; @@ -192,7 +192,7 @@ function prepareBidRequests(bidReq) { * @returns {object} */ function getMediaType(bidderRequest) { - return utils.deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; + return deepAccess(bidderRequest, 'mediaTypes.video') ? VIDEO : BANNER; } /** @@ -203,7 +203,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/openxAnalyticsAdapter.js b/modules/openxAnalyticsAdapter.js index 0c01d4b461e..f67f8bd0c75 100644 --- a/modules/openxAnalyticsAdapter.js +++ b/modules/openxAnalyticsAdapter.js @@ -1,10 +1,10 @@ +import { logInfo, logError, getWindowLocation, parseQS, logMessage, _each, deepAccess, logWarn, _map, flatten, uniques, isEmpty, parseSizesInput } from '../src/utils.js'; import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adapterManager from '../src/adapterManager.js'; import { ajax } from '../src/ajax.js'; import find from 'core-js-pure/features/array/find.js'; import includes from 'core-js-pure/features/array/includes.js'; -const utils = require('../src/utils.js'); export const AUCTION_STATES = { INIT: 'initialized', // auction has initialized @@ -92,7 +92,7 @@ openxAdapter.enableAnalytics = function(adapterConfig = {options: {}}) { // campaign properties defined by config will override utm query parameters analyticsConfig.campaign = {...buildCampaignFromUtmCodes(), ...analyticsConfig.campaign}; - utils.logInfo('OpenX Analytics enabled with config', analyticsConfig); + logInfo('OpenX Analytics enabled with config', analyticsConfig); // override track method with v2 handlers openxAdapter.track = prebidAnalyticsEventHandler; @@ -103,7 +103,7 @@ openxAdapter.enableAnalytics = function(adapterConfig = {options: {}}) { if (pubads.addEventListener) { pubads.addEventListener(SLOT_LOADED, args => { openxAdapter.track({eventType: SLOT_LOADED, args}); - utils.logInfo('OX: SlotOnLoad event triggered'); + logInfo('OX: SlotOnLoad event triggered'); }); } }); @@ -160,9 +160,9 @@ function isValidConfig({options: analyticsOptions}) { let [property, type, required] = failedValidation; if (required) { - utils.logError(`OpenXAnalyticsAdapter: Expected '${property}' to exist and of type '${type}'`); + logError(`OpenXAnalyticsAdapter: Expected '${property}' to exist and of type '${type}'`); } else { - utils.logError(`OpenXAnalyticsAdapter: Expected '${property}' to be type '${type}'`); + logError(`OpenXAnalyticsAdapter: Expected '${property}' to be type '${type}'`); } } @@ -170,8 +170,8 @@ function isValidConfig({options: analyticsOptions}) { } function buildCampaignFromUtmCodes() { - const location = utils.getWindowLocation(); - const queryParams = utils.parseQS(location && location.search); + const location = getWindowLocation(); + const queryParams = parseQS(location && location.search); let campaign = {}; UTM_TAGS.forEach(function(utmKey) { @@ -231,7 +231,7 @@ function detectBrowser() { } function prebidAnalyticsEventHandler({eventType, args}) { - utils.logMessage(eventType, Object.assign({}, args)); + logMessage(eventType, Object.assign({}, args)); switch (eventType) { case AUCTION_INIT: onAuctionInit(args); @@ -401,8 +401,8 @@ function onBidResponse(bidResponse) { } function onBidTimeout(args) { - utils._each(args, ({auctionId, adUnitCode, bidId: requestId}) => { - let timedOutRequest = utils.deepAccess(auctionMap, + _each(args, ({auctionId, adUnitCode, bidId: requestId}) => { + let timedOutRequest = deepAccess(auctionMap, `${auctionId}.adUnitCodeToAdUnitMap.${adUnitCode}.bidRequestsMap.${requestId}`); if (timedOutRequest) { @@ -433,7 +433,7 @@ function onAuctionEnd(endedAuction) { */ function onBidWon(bidResponse) { const { auctionId, adUnitCode, requestId, adId } = bidResponse; - let winningBid = utils.deepAccess(auctionMap, + let winningBid = deepAccess(auctionMap, `${auctionId}.adUnitCodeToAdUnitMap.${adUnitCode}.bidRequestsMap.${requestId}.bids.${adId}`); if (winningBid) { @@ -444,10 +444,10 @@ function onBidWon(bidResponse) { const bidder = auction.adUnitCodeToAdUnitMap[adUnitCode].bidRequestsMap[requestId].bidder; ajax(`${endpoint}?t=win&b=${adId}&a=${analyticsConfig.orgId}&bidder=${bidder}&ts=${auction.startTime}`, () => { - utils.logInfo(`Openx Analytics - Sending complete impression event for ${adId} at ${Date.now()}`) + logInfo(`Openx Analytics - Sending complete impression event for ${adId} at ${Date.now()}`) }); } else { - utils.logInfo(`Openx Analytics - impression event for ${adId} will be sent with auction data`) + logInfo(`Openx Analytics - impression event for ${adId} will be sent with auction data`) } } } @@ -522,7 +522,7 @@ function isAtf(elementId, scrollLeft = 0, scrollTop = 0) { } } } else { - utils.logWarn('OX: DOM element not for id ' + elementId); + logWarn('OX: DOM element not for id ' + elementId); } return isAtf; } @@ -552,7 +552,7 @@ function delayedSend(auction) { let payload = JSON.stringify([buildAuctionPayload(auction)]); ajax(analyticsConfig.endpoint || ENDPOINT, () => { - utils.logInfo(`OpenX Analytics - Sending complete auction at ${Date.now()}`); + logInfo(`OpenX Analytics - Sending complete auction at ${Date.now()}`); }, payload, { contentType: 'application/json' }); }, delayTime); } @@ -579,15 +579,15 @@ function getPathToBidResponseByBidId(bidId) { return []; } - utils._each(auctionMap, currentAuction => { + _each(auctionMap, currentAuction => { // skip completed auctions if (currentAuction.state === AUCTION_STATES.COMPLETED) { return; } - utils._each(currentAuction.adUnitCodeToAdUnitMap, (currentAdunit) => { - utils._each(currentAdunit.bidRequestsMap, currentBiddRequest => { - utils._each(currentBiddRequest.bids, (currentBidResponse, bidResponseId) => { + _each(currentAuction.adUnitCodeToAdUnitMap, (currentAdunit) => { + _each(currentAdunit.bidRequestsMap, currentBiddRequest => { + _each(currentBiddRequest.bids, (currentBidResponse, bidResponseId) => { if (bidId === bidResponseId) { auction = currentAuction; adUnit = currentAdunit; @@ -604,12 +604,12 @@ function getAuctionByGoogleTagSLot(slot) { let slotAdunitCodes = [slot.getSlotElementId(), slot.getAdUnitPath()]; let slotAuction; - utils._each(auctionMap, auction => { + _each(auctionMap, auction => { if (auction.state === AUCTION_STATES.COMPLETED) { return; } - utils._each(auction.adUnitCodeToAdUnitMap, (bidderRequestIdMap, adUnitCode) => { + _each(auction.adUnitCodeToAdUnitMap, (bidderRequestIdMap, adUnitCode) => { if (includes(slotAdunitCodes, adUnitCode)) { slotAuction = auction; } @@ -649,7 +649,7 @@ function buildAuctionPayload(auction) { }; function buildAdUnitsPayload(adUnitCodeToAdUnitMap) { - return utils._map(adUnitCodeToAdUnitMap, (adUnit) => { + return _map(adUnitCodeToAdUnitMap, (adUnit) => { let {code, adPosition} = adUnit; return { @@ -659,7 +659,7 @@ function buildAuctionPayload(auction) { }; function buildBidRequestPayload(bidRequestsMap) { - return utils._map(bidRequestsMap, (bidRequest) => { + return _map(bidRequestsMap, (bidRequest) => { let {bidder, source, bids, mediaTypes, timeLimit, timedOut} = bidRequest; return { bidder, @@ -669,7 +669,7 @@ function buildAuctionPayload(auction) { availableMediaTypes: getMediaTypes(mediaTypes), timeLimit, timedOut, - bidResponses: utils._map(bidRequest.bids, (bidderBidResponse) => { + bidResponses: _map(bidRequest.bids, (bidderBidResponse) => { let { adId, cpm, @@ -716,11 +716,11 @@ function buildAuctionPayload(auction) { } function buildUserIdProviders(userIds) { - return utils._map(userIds, (userId) => { - return utils._map(userId, (id, module) => { + return _map(userIds, (userId) => { + return _map(userId, (id, module) => { return hasUserData(module, id) ? module : false }).filter(module => module); - }).reduce(utils.flatten, []).filter(utils.uniques).sort(); + }).reduce(flatten, []).filter(uniques).sort(); } function hasUserData(module, idOrIdObject) { @@ -728,7 +728,7 @@ function buildAuctionPayload(auction) { switch (module) { case 'digitrustid': - normalizedId = utils.deepAccess(idOrIdObject, 'data.id'); + normalizedId = deepAccess(idOrIdObject, 'data.id'); break; case 'lipb': normalizedId = idOrIdObject.lipbid; @@ -737,17 +737,17 @@ function buildAuctionPayload(auction) { normalizedId = idOrIdObject; } - return !utils.isEmpty(normalizedId); + return !isEmpty(normalizedId); } function getMediaTypeSizes(mediaTypes) { - return utils._map(mediaTypes, (mediaTypeConfig, mediaType) => { - return utils.parseSizesInput(mediaTypeConfig.sizes) + return _map(mediaTypes, (mediaTypeConfig, mediaType) => { + return parseSizesInput(mediaTypeConfig.sizes) .map(size => `${mediaType}_${size}`); - }).reduce(utils.flatten, []); + }).reduce(flatten, []); } function getMediaTypes(mediaTypes) { - return utils._map(mediaTypes, (mediaTypeConfig, mediaType) => mediaType); + return _map(mediaTypes, (mediaTypeConfig, mediaType) => mediaType); } } diff --git a/modules/openxBidAdapter.js b/modules/openxBidAdapter.js index c3f3a7ddf42..f393ea87569 100644 --- a/modules/openxBidAdapter.js +++ b/modules/openxBidAdapter.js @@ -1,6 +1,6 @@ +import { deepAccess, convertTypes, isArray, inIframe, _map, deepSetValue, _each, parseSizesInput, parseUrl } from '../src/utils.js'; import {config} from '../src/config.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; -import * as utils from '../src/utils.js'; import {BANNER, VIDEO} from '../src/mediaTypes.js'; import includes from 'core-js-pure/features/array/includes.js' @@ -51,8 +51,8 @@ export const spec = { supportedMediaTypes: SUPPORTED_AD_TYPES, isBidRequestValid: function (bidRequest) { const hasDelDomainOrPlatform = bidRequest.params.delDomain || bidRequest.params.platform; - if (utils.deepAccess(bidRequest, 'mediaTypes.banner') && hasDelDomainOrPlatform) { - return !!bidRequest.params.unit || utils.deepAccess(bidRequest, 'mediaTypes.banner.sizes.length') > 0; + if (deepAccess(bidRequest, 'mediaTypes.banner') && hasDelDomainOrPlatform) { + return !!bidRequest.params.unit || deepAccess(bidRequest, 'mediaTypes.banner.sizes.length') > 0; } return !!(bidRequest.params.unit && hasDelDomainOrPlatform); @@ -87,8 +87,8 @@ export const spec = { getUserSyncs: function (syncOptions, responses, gdprConsent, uspConsent) { if (syncOptions.iframeEnabled || syncOptions.pixelEnabled) { let pixelType = syncOptions.iframeEnabled ? 'iframe' : 'image'; - let url = utils.deepAccess(responses, '0.body.ads.pixels') || - utils.deepAccess(responses, '0.body.pixels') || + let url = deepAccess(responses, '0.body.ads.pixels') || + deepAccess(responses, '0.body.pixels') || generateDefaultSyncUrl(gdprConsent, uspConsent); return [{ @@ -98,7 +98,7 @@ export const spec = { } }, transformBidParams: function(params, isOpenRtb) { - return utils.convertTypes({ + return convertTypes({ 'unit': 'string', 'customFloor': 'number' }, params); @@ -123,7 +123,7 @@ function generateDefaultSyncUrl(gdprConsent, uspConsent) { } function isVideoRequest(bidRequest) { - return (utils.deepAccess(bidRequest, 'mediaTypes.video') && !utils.deepAccess(bidRequest, 'mediaTypes.banner')) || bidRequest.mediaType === VIDEO; + return (deepAccess(bidRequest, 'mediaTypes.video') && !deepAccess(bidRequest, 'mediaTypes.banner')) || bidRequest.mediaType === VIDEO; } function createBannerBidResponses(oxResponseObj, {bids, startTime}) { @@ -215,7 +215,7 @@ function getViewportDimensions(isIfr) { function formatCustomParms(customKey, customParams) { let value = customParams[customKey]; - if (utils.isArray(value)) { + if (isArray(value)) { // if value is an array, join them with commas first value = value.join(','); } @@ -240,7 +240,7 @@ function getMediaTypeFromRequest(serverRequest) { } function buildCommonQueryParamsFromBids(bids, bidderRequest) { - const isInIframe = utils.inIframe(); + const isInIframe = inIframe(); let defaultParams; defaultParams = { @@ -252,7 +252,7 @@ function buildCommonQueryParamsFromBids(bids, bidderRequest) { tws: getViewportDimensions(isInIframe), be: 1, bc: bids[0].params.bc || `${BIDDER_CONFIG}_${BIDDER_VERSION}`, - dddid: utils._map(bids, bid => bid.transactionId).join(','), + dddid: _map(bids, bid => bid.transactionId).join(','), nocache: new Date().getTime() }; @@ -304,8 +304,8 @@ function buildCommonQueryParamsFromBids(bids, bidderRequest) { } // normalize publisher common id - if (utils.deepAccess(bids[0], 'crumbs.pubcid')) { - utils.deepSetValue(bids[0], 'userId.pubcid', utils.deepAccess(bids[0], 'crumbs.pubcid')); + if (deepAccess(bids[0], 'crumbs.pubcid')) { + deepSetValue(bids[0], 'userId.pubcid', deepAccess(bids[0], 'crumbs.pubcid')); } defaultParams = appendUserIdsToQueryParams(defaultParams, bids[0].userId); @@ -318,7 +318,7 @@ function buildCommonQueryParamsFromBids(bids, bidderRequest) { } function appendUserIdsToQueryParams(queryParams, userIds) { - utils._each(userIds, (userIdObjectOrValue, userIdProviderKey) => { + _each(userIds, (userIdObjectOrValue, userIdProviderKey) => { const key = USER_ID_CODE_TO_QUERY_ARG[userIdProviderKey]; if (USER_ID_CODE_TO_QUERY_ARG.hasOwnProperty(userIdProviderKey)) { @@ -371,13 +371,13 @@ function buildOXBannerRequest(bids, bidderRequest) { let customParamsForAllBids = []; let hasCustomParam = false; let queryParams = buildCommonQueryParamsFromBids(bids, bidderRequest); - let auids = utils._map(bids, bid => bid.params.unit); + let auids = _map(bids, bid => bid.params.unit); - queryParams.aus = utils._map(bids, bid => utils.parseSizesInput(bid.mediaTypes.banner.sizes).join(',')).join('|'); - queryParams.divids = utils._map(bids, bid => encodeURIComponent(bid.adUnitCode)).join(','); + queryParams.aus = _map(bids, bid => parseSizesInput(bid.mediaTypes.banner.sizes).join(',')).join('|'); + queryParams.divids = _map(bids, bid => encodeURIComponent(bid.adUnitCode)).join(','); // gpid - queryParams.aucs = utils._map(bids, function (bid) { - let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + queryParams.aucs = _map(bids, function (bid) { + let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); return encodeURIComponent(gpid || '') }).join(','); @@ -395,7 +395,7 @@ function buildOXBannerRequest(bids, bidderRequest) { bids.forEach(function (bid) { if (bid.params.customParams) { - let customParamsForBid = utils._map(Object.keys(bid.params.customParams), customKey => formatCustomParms(customKey, bid.params.customParams)); + let customParamsForBid = _map(Object.keys(bid.params.customParams), customKey => formatCustomParms(customKey, bid.params.customParams)); let formattedCustomParams = window.btoa(customParamsForBid.join('&')); hasCustomParam = true; customParamsForAllBids.push(formattedCustomParams); @@ -435,22 +435,22 @@ function buildOXVideoRequest(bid, bidderRequest) { } function generateVideoParameters(bid, bidderRequest) { - const videoMediaType = utils.deepAccess(bid, `mediaTypes.video`); + const videoMediaType = deepAccess(bid, `mediaTypes.video`); let queryParams = buildCommonQueryParamsFromBids([bid], bidderRequest); - let oxVideoConfig = utils.deepAccess(bid, 'params.video') || {}; - let context = utils.deepAccess(bid, 'mediaTypes.video.context'); - let playerSize = utils.deepAccess(bid, 'mediaTypes.video.playerSize'); + let oxVideoConfig = deepAccess(bid, 'params.video') || {}; + let context = deepAccess(bid, 'mediaTypes.video.context'); + let playerSize = deepAccess(bid, 'mediaTypes.video.playerSize'); let width; let height; // normalize config for video size - if (utils.isArray(bid.sizes) && bid.sizes.length === 2 && !utils.isArray(bid.sizes[0])) { + if (isArray(bid.sizes) && bid.sizes.length === 2 && !isArray(bid.sizes[0])) { width = parseInt(bid.sizes[0], 10); height = parseInt(bid.sizes[1], 10); - } else if (utils.isArray(bid.sizes) && utils.isArray(bid.sizes[0]) && bid.sizes[0].length === 2) { + } else if (isArray(bid.sizes) && isArray(bid.sizes[0]) && bid.sizes[0].length === 2) { width = parseInt(bid.sizes[0][0], 10); height = parseInt(bid.sizes[0][1], 10); - } else if (utils.isArray(playerSize) && playerSize.length === 2) { + } else if (isArray(playerSize) && playerSize.length === 2) { width = parseInt(playerSize[0], 10); height = parseInt(playerSize[1], 10); } @@ -463,7 +463,7 @@ function generateVideoParameters(bid, bidderRequest) { legacyParams = legacyParams.openrtb; } // support for video object or full openrtb object - if (utils.isArray(legacyParams.imp)) { + if (isArray(legacyParams.imp)) { legacyParams = legacyParams.imp[0].video; } Object.keys(legacyParams) @@ -502,7 +502,7 @@ function generateVideoParameters(bid, bidderRequest) { queryParams.vtest = 1; } - let gpid = utils.deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); + let gpid = deepAccess(bid, 'ortb2Imp.ext.data.pbadslot'); if (gpid) { queryParams.aucs = encodeURIComponent(gpid) } @@ -517,7 +517,7 @@ function createVideoBidResponses(response, {bid, startTime}) { let bidResponses = []; if (response !== undefined && response.vastUrl !== '' && response.pub_rev > 0) { - let vastQueryParams = utils.parseUrl(response.vastUrl).search || {}; + let vastQueryParams = parseUrl(response.vastUrl).search || {}; let bidResponse = {}; bidResponse.requestId = bid.bidId; if (response.deal_id) { diff --git a/modules/operaadsBidAdapter.js b/modules/operaadsBidAdapter.js index 6b7115b61d0..976b191d5de 100644 --- a/modules/operaadsBidAdapter.js +++ b/modules/operaadsBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logWarn, isArray, isStr, triggerPixel, deepAccess, deepSetValue, isPlainObject, generateUUID, parseUrl, isFn, getDNT, logError } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { config } from '../src/config.js'; import { BANNER, VIDEO, NATIVE } from '../src/mediaTypes.js'; @@ -70,27 +70,27 @@ export const spec = { */ isBidRequestValid: function (bid) { if (!bid) { - utils.logWarn(BIDDER_CODE, 'Invalid bid,', bid); + logWarn(BIDDER_CODE, 'Invalid bid,', bid); return false; } if (!bid.params) { - utils.logWarn(BIDDER_CODE, 'bid.params is required.') + logWarn(BIDDER_CODE, 'bid.params is required.') return false; } if (!bid.params.placementId) { - utils.logWarn(BIDDER_CODE, 'bid.params.placementId is required.') + logWarn(BIDDER_CODE, 'bid.params.placementId is required.') return false; } if (!bid.params.endpointId) { - utils.logWarn(BIDDER_CODE, 'bid.params.endpointId is required.') + logWarn(BIDDER_CODE, 'bid.params.endpointId is required.') return false; } if (!bid.params.publisherId) { - utils.logWarn(BIDDER_CODE, 'bid.params.publisherId is required.') + logWarn(BIDDER_CODE, 'bid.params.publisherId is required.') return false; } @@ -118,9 +118,9 @@ export const spec = { let bidResponses = []; let serverBody; - if ((serverBody = serverResponse.body) && serverBody.seatbid && utils.isArray(serverBody.seatbid)) { + if ((serverBody = serverResponse.body) && serverBody.seatbid && isArray(serverBody.seatbid)) { serverBody.seatbid.forEach((seatbidder) => { - if (seatbidder.bid && utils.isArray(seatbidder.bid)) { + if (seatbidder.bid && isArray(seatbidder.bid)) { bidResponses = seatbidder.bid.map((bid) => buildBidResponse(bid, bidRequest.originalBidRequest, serverBody)); } }); @@ -153,7 +153,7 @@ export const spec = { * @param {Bid} bid The bid that won the auction */ onBidWon: function (bid) { - if (!bid || !utils.isStr(bid.nurl)) { + if (!bid || !isStr(bid.nurl)) { return; } @@ -166,7 +166,7 @@ export const spec = { winCurr = bid.currency; } - utils.triggerPixel( + triggerPixel( bid.nurl .replace(/\$\{AUCTION_PRICE\}/g, winCpm) .replace(/\$\{AUCTION_CURRENCY\}/g, winCurr) @@ -189,7 +189,7 @@ export const spec = { * @returns {Request} */ function buildOpenRtbBidRequest(bidRequest, bidderRequest) { - const pageReferrer = utils.deepAccess(bidderRequest, 'refererInfo.referer'); + const pageReferrer = deepAccess(bidderRequest, 'refererInfo.referer'); // build OpenRTB request body const payload = { @@ -199,7 +199,7 @@ function buildOpenRtbBidRequest(bidRequest, bidderRequest) { imp: createImp(bidRequest), device: getDevice(), site: { - id: String(utils.deepAccess(bidRequest, 'params.publisherId')), + id: String(deepAccess(bidRequest, 'params.publisherId')), domain: getDomain(pageReferrer), page: pageReferrer, ref: window.self === window.top ? document.referrer : '', @@ -216,26 +216,26 @@ function buildOpenRtbBidRequest(bidRequest, bidderRequest) { } } - const gdprConsent = utils.deepAccess(bidderRequest, 'gdprConsent'); + const gdprConsent = deepAccess(bidderRequest, 'gdprConsent'); if (!!gdprConsent && gdprConsent.gdprApplies) { - utils.deepSetValue(payload, 'regs.ext.gdpr', 1); - utils.deepSetValue(payload, 'user.ext.consent', gdprConsent.consentString); + deepSetValue(payload, 'regs.ext.gdpr', 1); + deepSetValue(payload, 'user.ext.consent', gdprConsent.consentString); } - const uspConsent = utils.deepAccess(bidderRequest, 'uspConsent'); + const uspConsent = deepAccess(bidderRequest, 'uspConsent'); if (uspConsent) { - utils.deepSetValue(payload, 'regs.ext.us_privacy', uspConsent); + deepSetValue(payload, 'regs.ext.us_privacy', uspConsent); } - const eids = utils.deepAccess(bidRequest, 'userIdAsEids', []); + const eids = deepAccess(bidRequest, 'userIdAsEids', []); if (eids.length > 0) { - utils.deepSetValue(payload, 'user.eids', eids); + deepSetValue(payload, 'user.eids', eids); } return { method: 'POST', - url: ENDPOINT + String(utils.deepAccess(bidRequest, 'params.publisherId')) + - '?ep=' + String(utils.deepAccess(bidRequest, 'params.endpointId')), + url: ENDPOINT + String(deepAccess(bidRequest, 'params.publisherId')) + + '?ep=' + String(deepAccess(bidRequest, 'params.endpointId')), data: JSON.stringify(payload), options: { contentType: 'application/json', @@ -272,7 +272,7 @@ function buildBidResponse(bid, bidRequest, responseBody) { // OpenRtb Markup Response Object // https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-Native-Ads-Specification-1-1_2016.pdf#5.1 - if (markup && utils.isPlainObject(markup.native)) { + if (markup && isPlainObject(markup.native)) { mediaType = NATIVE; nativeResponse = markup.native; } @@ -281,7 +281,7 @@ function buildBidResponse(bid, bidRequest, responseBody) { const currency = responseBody.cur || DEFAULT_CURRENCY; const cpm = (parseFloat(bid.price) || 0).toFixed(2); - const categories = utils.deepAccess(bid, 'cat', []); + const categories = deepAccess(bid, 'cat', []); const bidResponse = { requestId: bid.impid, @@ -300,14 +300,14 @@ function buildBidResponse(bid, bidRequest, responseBody) { } }; - if (bid.adomain && utils.isArray(bid.adomain) && bid.adomain.length > 0) { + if (bid.adomain && isArray(bid.adomain) && bid.adomain.length > 0) { bidResponse.meta.advertiserDomains = bid.adomain; bidResponse.meta.clickUrl = bid.adomain[0]; } switch (mediaType) { case VIDEO: { - const playerSize = utils.deepAccess(bidRequest, 'mediaTypes.video.playerSize', VIDEO_DEFAULTS.SIZE); + const playerSize = deepAccess(bidRequest, 'mediaTypes.video.playerSize', VIDEO_DEFAULTS.SIZE); const size = canonicalizeSizesArray(playerSize)[0]; bidResponse.vastXml = bid.adm; @@ -315,7 +315,7 @@ function buildBidResponse(bid, bidRequest, responseBody) { bidResponse.width = bid.w || size[0]; bidResponse.height = bid.h || size[1]; - const context = utils.deepAccess(bidRequest, 'mediaTypes.video.context'); + const context = deepAccess(bidRequest, 'mediaTypes.video.context'); // if outstream video, add a default render for it. if (context === OUTSTREAM) { @@ -358,13 +358,13 @@ function interpretNativeAd(nativeResponse, currency, cpm) { // OpenRtb Link Object // https://www.iab.com/wp-content/uploads/2016/03/OpenRTB-Native-Ads-Specification-1-1_2016.pdf#5.7 - const clickUrl = utils.deepAccess(nativeResponse, 'link.url'); - if (clickUrl && utils.isStr(clickUrl)) { + const clickUrl = deepAccess(nativeResponse, 'link.url'); + if (clickUrl && isStr(clickUrl)) { native.clickUrl = decodeURIComponent(clickUrl); } - const clickTrackers = utils.deepAccess(nativeResponse, 'link.clicktrackers'); - if (clickTrackers && utils.isArray(clickTrackers)) { + const clickTrackers = deepAccess(nativeResponse, 'link.clicktrackers'); + if (clickTrackers && isArray(clickTrackers)) { native.clickTrackers = clickTrackers .filter(Boolean) .map( @@ -374,7 +374,7 @@ function interpretNativeAd(nativeResponse, currency, cpm) { ); } - if (nativeResponse.imptrackers && utils.isArray(nativeResponse.imptrackers)) { + if (nativeResponse.imptrackers && isArray(nativeResponse.imptrackers)) { native.impressionTrackers = nativeResponse.imptrackers .filter(Boolean) .map( @@ -384,16 +384,16 @@ function interpretNativeAd(nativeResponse, currency, cpm) { ); } - if (nativeResponse.jstracker && utils.isStr(nativeResponse.jstracker)) { + if (nativeResponse.jstracker && isStr(nativeResponse.jstracker)) { native.javascriptTrackers = [nativeResponse.jstracker]; } let assets; - if ((assets = nativeResponse.assets) && utils.isArray(assets)) { + if ((assets = nativeResponse.assets) && isArray(assets)) { assets.forEach((asset) => { switch (asset.id) { case NATIVE_DEFAULTS.ASSET_ID.TITLE: { - const title = utils.deepAccess(asset, 'title.text'); + const title = deepAccess(asset, 'title.text'); if (title) { native.title = title; } @@ -420,21 +420,21 @@ function interpretNativeAd(nativeResponse, currency, cpm) { break; } case NATIVE_DEFAULTS.ASSET_ID.BODY: { - const body = utils.deepAccess(asset, 'data.value'); + const body = deepAccess(asset, 'data.value'); if (body) { native.body = body; } break; } case NATIVE_DEFAULTS.ASSET_ID.SPONSORED: { - const sponsoredBy = utils.deepAccess(asset, 'data.value'); + const sponsoredBy = deepAccess(asset, 'data.value'); if (sponsoredBy) { native.sponsoredBy = sponsoredBy; } break; } case NATIVE_DEFAULTS.ASSET_ID.CTA: { - const cta = utils.deepAccess(asset, 'data.value'); + const cta = deepAccess(asset, 'data.value'); if (cta) { native.cta = cta; } @@ -459,13 +459,13 @@ function createImp(bidRequest) { const impItem = { id: bidRequest.bidId, - tagid: String(utils.deepAccess(bidRequest, 'params.placementId')), + tagid: String(deepAccess(bidRequest, 'params.placementId')), }; let mediaType, size; let bannerReq, videoReq, nativeReq; - if ((bannerReq = utils.deepAccess(bidRequest, 'mediaTypes.banner'))) { + if ((bannerReq = deepAccess(bidRequest, 'mediaTypes.banner'))) { size = canonicalizeSizesArray(bannerReq.sizes || BANNER_DEFAULTS.SIZE)[0]; impItem.banner = { @@ -475,7 +475,7 @@ function createImp(bidRequest) { }; mediaType = BANNER; - } else if ((videoReq = utils.deepAccess(bidRequest, 'mediaTypes.video'))) { + } else if ((videoReq = deepAccess(bidRequest, 'mediaTypes.video'))) { size = canonicalizeSizesArray(videoReq.playerSize || VIDEO_DEFAULTS.SIZE)[0]; impItem.video = { @@ -493,7 +493,7 @@ function createImp(bidRequest) { }; mediaType = VIDEO; - } else if ((nativeReq = utils.deepAccess(bidRequest, 'mediaTypes.native'))) { + } else if ((nativeReq = deepAccess(bidRequest, 'mediaTypes.native'))) { const params = bidRequest.nativeParams || nativeReq; const request = { @@ -533,7 +533,7 @@ function createImp(bidRequest) { * @returns {Size[][]} */ function canonicalizeSizesArray(sizes) { - if (sizes.length === 2 && !utils.isArray(sizes[0])) { + if (sizes.length === 2 && !isArray(sizes[0])) { return [sizes]; } return sizes; @@ -645,19 +645,19 @@ function mapNativeImage(image, type) { * @returns {String} userId */ function getUserId(bidRequest) { - let sharedId = utils.deepAccess(bidRequest, 'userId.sharedid.id'); + let sharedId = deepAccess(bidRequest, 'userId.sharedid.id'); if (sharedId) { return sharedId; } for (const idModule of ['pubcid', 'tdid']) { - let userId = utils.deepAccess(bidRequest, `userId.${idModule}`); + let userId = deepAccess(bidRequest, `userId.${idModule}`); if (userId) { return userId; } } - return utils.generateUUID(); + return generateUUID(); } /** @@ -670,7 +670,7 @@ function getDomain(referer) { let domain; if (!(domain = config.getConfig('publisherDomain'))) { - const u = utils.parseUrl(referer); + const u = parseUrl(referer); domain = u.hostname; } @@ -685,14 +685,14 @@ function getDomain(referer) { * @returns {Floor} floor price */ function getBidFloor(bid, {mediaType = '*', size = '*'}) { - if (utils.isFn(bid.getFloor)) { + if (isFn(bid.getFloor)) { const floorInfo = bid.getFloor({ currency: DEFAULT_CURRENCY, mediaType, size }); - if (utils.isPlainObject(floorInfo) && !isNaN(floorInfo.floor)) { + if (isPlainObject(floorInfo) && !isNaN(floorInfo.floor)) { return { currency: floorInfo.currency || DEFAULT_CURRENCY, floor: floorInfo.floor @@ -715,7 +715,7 @@ function getBidFloor(bid, {mediaType = '*', size = '*'}) { function getBcat(bidRequest) { let bcat = []; - const pBcat = utils.deepAccess(bidRequest, 'params.bcat'); + const pBcat = deepAccess(bidRequest, 'params.bcat'); if (pBcat) { bcat = bcat.concat(pBcat); } @@ -736,7 +736,7 @@ function getDevice() { device.ua = device.ua || navigator.userAgent; device.language = device.language || getLanguage(); device.dnt = typeof device.dnt === 'number' - ? device.dnt : (utils.getDNT() ? 1 : 0); + ? device.dnt : (getDNT() ? 1 : 0); return device; } @@ -759,8 +759,8 @@ function getLanguage() { * @returns */ function createRenderer(bidRequest) { - const globalRenderer = utils.deepAccess(bidRequest, 'renderer'); - const currentRenderer = utils.deepAccess(bidRequest, 'mediaTypes.video.renderer'); + const globalRenderer = deepAccess(bidRequest, 'renderer'); + const currentRenderer = deepAccess(bidRequest, 'mediaTypes.video.renderer'); let url = OUTSTREAM_RENDERER_URL; let config = {}; @@ -795,7 +795,7 @@ function createRenderer(bidRequest) { try { renderer.setRender(render); } catch (e) { - utils.logError(BIDDER_CODE, 'Error calling setRender on renderer', e); + logError(BIDDER_CODE, 'Error calling setRender on renderer', e); } return renderer; } diff --git a/modules/optimeraRtdProvider.js b/modules/optimeraRtdProvider.js index 1e439b28c94..b7ce3c6c6d9 100644 --- a/modules/optimeraRtdProvider.js +++ b/modules/optimeraRtdProvider.js @@ -18,7 +18,7 @@ * @property {string} device */ -import * as utils from '../src/utils.js'; +import { logInfo, logError } from '../src/utils.js'; import { submodule } from '../src/hook.js'; import { ajaxBuilder } from '../src/ajax.js'; @@ -74,7 +74,7 @@ export let fetchScoreFile = true; * Make the request for the Score File. */ export function scoreFileRequest() { - utils.logInfo('Fetch Optimera score file.'); + logInfo('Fetch Optimera score file.'); const ajax = ajaxBuilder(); ajax(scoresURL, { @@ -83,14 +83,14 @@ export function scoreFileRequest() { try { setScores(res); } catch (err) { - utils.logError('Unable to parse Optimera Score File.', err); + logError('Unable to parse Optimera Score File.', err); } } else if (req.status === 403) { - utils.logError('Unable to fetch the Optimera Score File - 403'); + logError('Unable to fetch the Optimera Score File - 403'); } }, error: () => { - utils.logError('Unable to fetch the Optimera Score File.'); + logError('Unable to fetch the Optimera Score File.'); } }); } @@ -108,9 +108,9 @@ export function returnTargetingData(adUnits, config) { } }); } catch (err) { - utils.logError('error', err); + logError('error', err); } - utils.logInfo('Apply Optimera targeting'); + logInfo('Apply Optimera targeting'); return targeting; } @@ -143,7 +143,7 @@ export function init(moduleConfig) { return true; } else { if (!_moduleParams.clientID) { - utils.logError('Optimera clientID is missing in the Optimera RTD configuration.'); + logError('Optimera clientID is missing in the Optimera RTD configuration.'); } return false; } @@ -185,7 +185,7 @@ export function setScores(result) { scores = scores.device[device]; } } catch (e) { - utils.logError('Optimera score file could not be parsed.'); + logError('Optimera score file could not be parsed.'); } optimeraTargeting = scores; } diff --git a/modules/optoutBidAdapter.js b/modules/optoutBidAdapter.js index 3a2e672013c..d218a65bf90 100644 --- a/modules/optoutBidAdapter.js +++ b/modules/optoutBidAdapter.js @@ -1,11 +1,11 @@ -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'; const BIDDER_CODE = 'optout'; function getDomain(bidderRequest) { - return utils.deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || utils.deepAccess(window, 'location.href'); + return deepAccess(bidderRequest, 'refererInfo.canonicalUrl') || deepAccess(window, 'location.href'); } function getCurrency() { @@ -23,7 +23,7 @@ function hasPurpose1Consent(bidderRequest) { let result = false; if (bidderRequest && bidderRequest.gdprConsent) { if (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; diff --git a/modules/orbidderBidAdapter.js b/modules/orbidderBidAdapter.js index edd44385d52..111c1876e14 100644 --- a/modules/orbidderBidAdapter.js +++ b/modules/orbidderBidAdapter.js @@ -1,7 +1,7 @@ +import { isFn, isPlainObject } from '../src/utils.js'; import {registerBidder} from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; const storageManager = getStorageManager(); @@ -146,7 +146,7 @@ export const spec = { * @returns {float||undefined} */ function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return bid.params.bidfloor; } @@ -155,7 +155,7 @@ function getBidFloor(bid) { mediaType: '*', size: '*' }); - if (utils.isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'EUR') { + if (isPlainObject(floor) && !isNaN(floor.floor) && floor.currency === 'EUR') { return floor.floor; } return undefined; diff --git a/modules/outbrainBidAdapter.js b/modules/outbrainBidAdapter.js index 052122e95f1..3dd9c67dc98 100644 --- a/modules/outbrainBidAdapter.js +++ b/modules/outbrainBidAdapter.js @@ -5,7 +5,7 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { NATIVE, BANNER } from '../src/mediaTypes.js'; -import * as utils from '../src/utils.js'; +import { deepAccess, deepSetValue, replaceAuctionPrice, _map, isArray } from '../src/utils.js'; import { ajax } from '../src/ajax.js'; import { config } from '../src/config.js'; @@ -29,7 +29,7 @@ export const spec = { isBidRequestValid: (bid) => { return ( !!config.getConfig('outbrain.bidderUrl') && - !!utils.deepAccess(bid, 'params.publisher.id') && + !!deepAccess(bid, 'params.publisher.id') && !!(bid.nativeParams || bid.sizes) ); }, @@ -94,15 +94,15 @@ export const spec = { request.test = 1; } - if (utils.deepAccess(bidderRequest, 'gdprConsent.gdprApplies')) { - utils.deepSetValue(request, 'user.ext.consent', bidderRequest.gdprConsent.consentString) - utils.deepSetValue(request, 'regs.ext.gdpr', bidderRequest.gdprConsent.gdprApplies & 1) + if (deepAccess(bidderRequest, 'gdprConsent.gdprApplies')) { + 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 (config.getConfig('coppa') === true) { - utils.deepSetValue(request, 'regs.coppa', config.getConfig('coppa') & 1) + deepSetValue(request, 'regs.coppa', config.getConfig('coppa') & 1) } return { @@ -177,7 +177,7 @@ export const spec = { // for native requests we put the nurl as an imp tracker, otherwise if the auction takes place on prebid server // the server JS adapter puts the nurl in the adm as a tracking pixel and removes the attribute if (bid.nurl) { - ajax(utils.replaceAuctionPrice(bid.nurl, bid.originalCpm)) + ajax(replaceAuctionPrice(bid.nurl, bid.originalCpm)) } } }; @@ -216,7 +216,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; } @@ -228,7 +228,7 @@ function flatten(arr) { } function getNativeAssets(bid) { - return utils._map(bid.nativeParams, (bidParams, key) => { + return _map(bid.nativeParams, (bidParams, key) => { const props = NATIVE_PARAMS[key]; const asset = { required: bidParams.required & 1, @@ -266,16 +266,16 @@ function getNativeAssets(bid) { /* Turn bid request sizes into ut-compatible format */ function transformSizes(requestSizes) { - if (!utils.isArray(requestSizes)) { + if (!isArray(requestSizes)) { return []; } - if (requestSizes.length === 2 && !utils.isArray(requestSizes[0])) { + if (requestSizes.length === 2 && !isArray(requestSizes[0])) { return [{ w: parseInt(requestSizes[0], 10), h: parseInt(requestSizes[1], 10) }]; - } else if (utils.isArray(requestSizes[0])) { + } else if (isArray(requestSizes[0])) { return requestSizes.map(item => ({ w: parseInt(item[0], 10), diff --git a/modules/ozoneBidAdapter.js b/modules/ozoneBidAdapter.js index 974fe3a4304..5b46a2cb80b 100644 --- a/modules/ozoneBidAdapter.js +++ b/modules/ozoneBidAdapter.js @@ -1,4 +1,4 @@ -import * as utils from '../src/utils.js'; +import { logInfo, logError, deepAccess, logWarn, deepSetValue, isArray, contains, isStr, mergeDeep } 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'; @@ -41,7 +41,7 @@ export const spec = { this.propertyBag.whitelabel.logId = bidder.toUpperCase(); this.propertyBag.whitelabel.bidder = bidder; let bidderConfig = config.getConfig(bidder) || {}; - utils.logInfo('got bidderConfig: ', JSON.parse(JSON.stringify(bidderConfig))); + logInfo('got bidderConfig: ', JSON.parse(JSON.stringify(bidderConfig))); if (bidderConfig.kvpPrefix) { this.propertyBag.whitelabel.keyPrefix = bidderConfig.kvpPrefix; } @@ -71,15 +71,15 @@ export const spec = { } try { if (arr.hasOwnProperty('auction') && arr.auction === 'dev') { - utils.logInfo('GET: auction=dev'); + logInfo('GET: auction=dev'); this.propertyBag.whitelabel.auctionUrl = ORIGIN_DEV + AUCTIONURI; } if (arr.hasOwnProperty('cookiesync') && arr.cookiesync === 'dev') { - utils.logInfo('GET: cookiesync=dev'); + logInfo('GET: cookiesync=dev'); this.propertyBag.whitelabel.cookieSyncUrl = ORIGIN_DEV + OZONECOOKIESYNC; } } catch (e) {} - utils.logInfo('set propertyBag.whitelabel to', this.propertyBag.whitelabel); + logInfo('set propertyBag.whitelabel to', this.propertyBag.whitelabel); }, getAuctionUrl() { return this.propertyBag.whitelabel.auctionUrl; @@ -97,62 +97,62 @@ export const spec = { */ isBidRequestValid(bid) { this.loadWhitelabelData(bid); - utils.logInfo('isBidRequestValid : ', config.getConfig(), bid); + logInfo('isBidRequestValid : ', config.getConfig(), bid); let adUnitCode = bid.adUnitCode; // adunit[n].code if (!(bid.params.hasOwnProperty('placementId'))) { - utils.logError('VALIDATION FAILED : missing placementId : siteId, placementId and publisherId are REQUIRED', adUnitCode); + logError('VALIDATION FAILED : missing placementId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!this.isValidPlacementId(bid.params.placementId)) { - utils.logError('VALIDATION FAILED : placementId must be exactly 10 numeric characters', adUnitCode); + logError('VALIDATION FAILED : placementId must be exactly 10 numeric characters', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('publisherId'))) { - utils.logError('VALIDATION FAILED : missing publisherId : siteId, placementId and publisherId are REQUIRED', adUnitCode); + logError('VALIDATION FAILED : missing publisherId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!(bid.params.publisherId).toString().match(/^[a-zA-Z0-9\-]{12}$/)) { - utils.logError('VALIDATION FAILED : publisherId must be exactly 12 alphanumieric characters including hyphens', adUnitCode); + logError('VALIDATION FAILED : publisherId must be exactly 12 alphanumieric characters including hyphens', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('siteId'))) { - utils.logError('VALIDATION FAILED : missing siteId : siteId, placementId and publisherId are REQUIRED', adUnitCode); + logError('VALIDATION FAILED : missing siteId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!(bid.params.siteId).toString().match(/^[0-9]{10}$/)) { - utils.logError('VALIDATION FAILED : siteId must be exactly 10 numeric characters', adUnitCode); + logError('VALIDATION FAILED : siteId must be exactly 10 numeric characters', adUnitCode); return false; } if (bid.params.hasOwnProperty('customParams')) { - utils.logError('VALIDATION FAILED : customParams should be renamed to customData', adUnitCode); + logError('VALIDATION FAILED : customParams should be renamed to customData', adUnitCode); return false; } if (bid.params.hasOwnProperty('customData')) { if (!Array.isArray(bid.params.customData)) { - utils.logError('VALIDATION FAILED : customData is not an Array', adUnitCode); + logError('VALIDATION FAILED : customData is not an Array', adUnitCode); return false; } if (bid.params.customData.length < 1) { - utils.logError('VALIDATION FAILED : customData is an array but does not contain any elements', adUnitCode); + logError('VALIDATION FAILED : customData is an array but does not contain any elements', adUnitCode); return false; } if (!(bid.params.customData[0]).hasOwnProperty('targeting')) { - utils.logError('VALIDATION FAILED : customData[0] does not contain "targeting"', adUnitCode); + logError('VALIDATION FAILED : customData[0] does not contain "targeting"', adUnitCode); return false; } if (typeof bid.params.customData[0]['targeting'] != 'object') { - utils.logError('VALIDATION FAILED : customData[0] targeting is not an object', adUnitCode); + logError('VALIDATION FAILED : customData[0] targeting is not an object', adUnitCode); return false; } } if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('context')) { - utils.logError('No video context key/value in bid. Rejecting bid: ', bid); + logError('No video context key/value in bid. Rejecting bid: ', bid); return false; } if (bid.mediaTypes[VIDEO].context !== 'instream' && bid.mediaTypes[VIDEO].context !== 'outstream') { - utils.logError('video.context is invalid. Only instream/outstream video is supported. Rejecting bid: ', bid); + logError('video.context is invalid. Only instream/outstream video is supported. Rejecting bid: ', bid); return false; } } @@ -172,7 +172,7 @@ export const spec = { this.propertyBag.buildRequestsStart = new Date().getTime(); let whitelabelBidder = this.propertyBag.whitelabel.bidder; // by default = ozone let whitelabelPrefix = this.propertyBag.whitelabel.keyPrefix; - utils.logInfo(`buildRequests time: ${this.propertyBag.buildRequestsStart} v ${OZONEVERSION} validBidRequests`, JSON.parse(JSON.stringify(validBidRequests)), 'bidderRequest', JSON.parse(JSON.stringify(bidderRequest))); + logInfo(`buildRequests time: ${this.propertyBag.buildRequestsStart} v ${OZONEVERSION} validBidRequests`, JSON.parse(JSON.stringify(validBidRequests)), 'bidderRequest', JSON.parse(JSON.stringify(bidderRequest))); // First check - is there any config to block this request? if (this.blockTheRequest()) { return []; @@ -180,21 +180,21 @@ export const spec = { let htmlParams = {'publisherId': '', 'siteId': ''}; if (validBidRequests.length > 0) { this.cookieSyncBag.userIdObject = Object.assign(this.cookieSyncBag.userIdObject, this.findAllUserIds(validBidRequests[0])); - this.cookieSyncBag.siteId = utils.deepAccess(validBidRequests[0], 'params.siteId'); - this.cookieSyncBag.publisherId = utils.deepAccess(validBidRequests[0], 'params.publisherId'); + this.cookieSyncBag.siteId = deepAccess(validBidRequests[0], 'params.siteId'); + this.cookieSyncBag.publisherId = deepAccess(validBidRequests[0], 'params.publisherId'); htmlParams = validBidRequests[0].params; } - utils.logInfo('cookie sync bag', this.cookieSyncBag); + logInfo('cookie sync bag', this.cookieSyncBag); let singleRequest = this.getWhitelabelConfigItem('ozone.singleRequest'); singleRequest = singleRequest !== false; // undefined & true will be true - utils.logInfo(`config ${whitelabelBidder}.singleRequest : `, singleRequest); + logInfo(`config ${whitelabelBidder}.singleRequest : `, singleRequest); let ozoneRequest = {}; // we only want to set specific properties on this, not validBidRequests[0].params delete ozoneRequest.test; // don't allow test to be set in the config - ONLY use $_GET['pbjs_debug'] // First party data module : look for ortb2 in setconfig & set the User object. NOTE THAT this should happen before we set the consentString let fpd = config.getConfig('ortb2'); - if (fpd && utils.deepAccess(fpd, 'user')) { - utils.logInfo('added FPD user object'); + if (fpd && deepAccess(fpd, 'user')) { + logInfo('added FPD user object'); ozoneRequest.user = fpd.user; } @@ -214,53 +214,53 @@ export const spec = { let arrBannerSizes = []; if (!ozoneBidRequest.hasOwnProperty('mediaTypes')) { if (ozoneBidRequest.hasOwnProperty('sizes')) { - utils.logInfo('no mediaTypes detected - will use the sizes array in the config root'); + logInfo('no mediaTypes detected - will use the sizes array in the config root'); arrBannerSizes = ozoneBidRequest.sizes; } else { - utils.logInfo('no mediaTypes detected, no sizes array in the config root either. Cannot set sizes for banner type'); + logInfo('no mediaTypes detected, no sizes array in the config root either. Cannot set sizes for banner type'); } } else { if (ozoneBidRequest.mediaTypes.hasOwnProperty(BANNER)) { arrBannerSizes = ozoneBidRequest.mediaTypes[BANNER].sizes; /* Note - if there is a sizes element in the config root it will be pushed into here */ - utils.logInfo('setting banner size from the mediaTypes.banner element for bidId ' + obj.id + ': ', arrBannerSizes); + logInfo('setting banner size from the mediaTypes.banner element for bidId ' + obj.id + ': ', arrBannerSizes); } if (ozoneBidRequest.mediaTypes.hasOwnProperty(VIDEO)) { - utils.logInfo('openrtb 2.5 compliant video'); + logInfo('openrtb 2.5 compliant video'); // examine all the video attributes in the config, and either put them into obj.video if allowed by IAB2.5 or else in to obj.video.ext if (typeof ozoneBidRequest.mediaTypes[VIDEO] == 'object') { - let childConfig = utils.deepAccess(ozoneBidRequest, 'params.video', {}); + let childConfig = deepAccess(ozoneBidRequest, 'params.video', {}); obj.video = this.unpackVideoConfigIntoIABformat(ozoneBidRequest.mediaTypes[VIDEO], childConfig); obj.video = this.addVideoDefaults(obj.video, ozoneBidRequest.mediaTypes[VIDEO], childConfig); } // we need to duplicate some of the video values let wh = getWidthAndHeightFromVideoObject(obj.video); - utils.logInfo('setting video object from the mediaTypes.video element: ' + obj.id + ':', obj.video, 'wh=', wh); + logInfo('setting video object from the mediaTypes.video element: ' + obj.id + ':', obj.video, 'wh=', wh); if (wh && typeof wh === 'object') { obj.video.w = wh['w']; obj.video.h = wh['h']; if (playerSizeIsNestedArray(obj.video)) { // this should never happen; it was in the original spec for this change though. - utils.logInfo('setting obj.video.format to be an array of objects'); + logInfo('setting obj.video.format to be an array of objects'); obj.video.ext.format = [wh]; } else { - utils.logInfo('setting obj.video.format to be an object'); + logInfo('setting obj.video.format to be an object'); obj.video.ext.format = wh; } } else { - utils.logWarn('cannot set w, h & format values for video; the config is not right'); + logWarn('cannot set w, h & format values for video; the config is not right'); } } // Native integration is not complete yet if (ozoneBidRequest.mediaTypes.hasOwnProperty(NATIVE)) { obj.native = ozoneBidRequest.mediaTypes[NATIVE]; - utils.logInfo('setting native object from the mediaTypes.native element: ' + obj.id + ':', obj.native); + logInfo('setting native object from the mediaTypes.native element: ' + obj.id + ':', obj.native); } // is the publisher specifying floors, and is the floors module enabled? if (ozoneBidRequest.hasOwnProperty('getFloor')) { - utils.logInfo('This bidRequest object has property: getFloor'); + logInfo('This bidRequest object has property: getFloor'); obj.floor = this.getFloorObjectForAuction(ozoneBidRequest); - utils.logInfo('obj.floor is : ', obj.floor); + logInfo('obj.floor is : ', obj.floor); } else { - utils.logInfo('This bidRequest object DOES NOT have property: getFloor'); + logInfo('This bidRequest object DOES NOT have property: getFloor'); } } if (arrBannerSizes.length > 0) { @@ -277,7 +277,7 @@ export const spec = { // these 3 MUST exist - we check them in the validation method obj.placementId = placementId; // build the imp['ext'] object - NOTE - Dont obliterate anything that' already in obj.ext - utils.deepSetValue(obj, 'ext.prebid', {'storedrequest': {'id': placementId}}); + deepSetValue(obj, 'ext.prebid', {'storedrequest': {'id': placementId}}); // obj.ext = {'prebid': {'storedrequest': {'id': placementId}}}; obj.ext[whitelabelBidder] = {}; obj.ext[whitelabelBidder].adUnitCode = ozoneBidRequest.adUnitCode; // eg. 'mpu' @@ -285,9 +285,9 @@ export const spec = { if (ozoneBidRequest.params.hasOwnProperty('customData')) { obj.ext[whitelabelBidder].customData = ozoneBidRequest.params.customData; } - utils.logInfo(`obj.ext.${whitelabelBidder} is `, obj.ext[whitelabelBidder]); + logInfo(`obj.ext.${whitelabelBidder} is `, obj.ext[whitelabelBidder]); if (isTestMode != null) { - utils.logInfo('setting isTestMode to ', isTestMode); + logInfo('setting isTestMode to ', isTestMode); if (obj.ext[whitelabelBidder].hasOwnProperty('customData')) { for (let i = 0; i < obj.ext[whitelabelBidder].customData.length; i++) { obj.ext[whitelabelBidder].customData[i]['targeting'][wlOztestmodeKey] = isTestMode; @@ -297,17 +297,17 @@ export const spec = { obj.ext[whitelabelBidder].customData[0].targeting[wlOztestmodeKey] = isTestMode; } } - if (fpd && utils.deepAccess(fpd, 'site')) { + if (fpd && deepAccess(fpd, 'site')) { // attach the site fpd into exactly : imp[n].ext.[whitelabel].customData.0.targeting - utils.logInfo('added FPD site object'); - if (utils.deepAccess(obj, 'ext.' + whitelabelBidder + '.customData.0.targeting', false)) { + logInfo('added FPD site object'); + if (deepAccess(obj, 'ext.' + whitelabelBidder + '.customData.0.targeting', false)) { obj.ext[whitelabelBidder].customData[0].targeting = Object.assign(obj.ext[whitelabelBidder].customData[0].targeting, fpd.site); - // let keys = utils.getKeys(fpd.site); + // let keys = getKeys(fpd.site); // for (let i = 0; i < keys.length; i++) { // obj.ext[whitelabelBidder].customData[0].targeting[keys[i]] = fpd.site[keys[i]]; // } } else { - utils.deepSetValue(obj, 'ext.' + whitelabelBidder + '.customData.0.targeting', fpd.site); + deepSetValue(obj, 'ext.' + whitelabelBidder + '.customData.0.targeting', fpd.site); } } return obj; @@ -327,17 +327,17 @@ export const spec = { } extObj[whitelabelBidder].pv = this.getPageId(); // attach the page ID that will be common to all auciton calls for this page if refresh() is called let ozOmpFloorDollars = this.getWhitelabelConfigItem('ozone.oz_omp_floor'); // valid only if a dollar value (typeof == 'number') - utils.logInfo(`${whitelabelPrefix}_omp_floor dollar value = `, ozOmpFloorDollars); + logInfo(`${whitelabelPrefix}_omp_floor dollar value = `, ozOmpFloorDollars); if (typeof ozOmpFloorDollars === 'number') { extObj[whitelabelBidder][whitelabelPrefix + '_omp_floor'] = ozOmpFloorDollars; } else if (typeof ozOmpFloorDollars !== 'undefined') { - utils.logError(`${whitelabelPrefix}_omp_floor is invalid - IF SET then this must be a number, representing dollar value eg. ${whitelabelPrefix}_omp_floor: 1.55. You have it set as a ` + (typeof ozOmpFloorDollars)); + logError(`${whitelabelPrefix}_omp_floor is invalid - IF SET then this must be a number, representing dollar value eg. ${whitelabelPrefix}_omp_floor: 1.55. You have it set as a ` + (typeof ozOmpFloorDollars)); } let ozWhitelistAdserverKeys = this.getWhitelabelConfigItem('ozone.oz_whitelist_adserver_keys'); - let useOzWhitelistAdserverKeys = utils.isArray(ozWhitelistAdserverKeys) && ozWhitelistAdserverKeys.length > 0; + let useOzWhitelistAdserverKeys = isArray(ozWhitelistAdserverKeys) && ozWhitelistAdserverKeys.length > 0; extObj[whitelabelBidder][whitelabelPrefix + '_kvp_rw'] = useOzWhitelistAdserverKeys ? 1 : 0; if (whitelabelBidder != 'ozone') { - utils.logInfo('setting aliases object'); + logInfo('setting aliases object'); extObj.prebid = {aliases: {'ozone': whitelabelBidder}}; } // 20210413 - adding a set of GET params to pass to auction @@ -359,53 +359,53 @@ export const spec = { // this should come as late as possible so it overrides any user.ext.consent value if (bidderRequest && bidderRequest.gdprConsent) { - utils.logInfo('ADDING GDPR info'); - let apiVersion = utils.deepAccess(bidderRequest, 'gdprConsent.apiVersion', 1); + logInfo('ADDING GDPR info'); + let apiVersion = deepAccess(bidderRequest, 'gdprConsent.apiVersion', 1); ozoneRequest.regs = {ext: {gdpr: bidderRequest.gdprConsent.gdprApplies ? 1 : 0, apiVersion: apiVersion}}; - if (utils.deepAccess(ozoneRequest, 'regs.ext.gdpr')) { - utils.deepSetValue(ozoneRequest, 'user.ext.consent', bidderRequest.gdprConsent.consentString); + if (deepAccess(ozoneRequest, 'regs.ext.gdpr')) { + deepSetValue(ozoneRequest, 'user.ext.consent', bidderRequest.gdprConsent.consentString); } else { - utils.logInfo('**** Strange CMP info: bidderRequest.gdprConsent exists BUT bidderRequest.gdprConsent.gdprApplies is false. See bidderRequest logged above. ****'); + logInfo('**** Strange CMP info: bidderRequest.gdprConsent exists BUT bidderRequest.gdprConsent.gdprApplies is false. See bidderRequest logged above. ****'); } } else { - utils.logInfo('WILL NOT ADD GDPR info; no bidderRequest.gdprConsent object'); + logInfo('WILL NOT ADD GDPR info; no bidderRequest.gdprConsent object'); } if (bidderRequest && bidderRequest.uspConsent) { - utils.logInfo('ADDING CCPA info'); - utils.deepSetValue(ozoneRequest, 'user.ext.uspConsent', bidderRequest.uspConsent); + logInfo('ADDING CCPA info'); + deepSetValue(ozoneRequest, 'user.ext.uspConsent', bidderRequest.uspConsent); } else { - utils.logInfo('WILL NOT ADD CCPA info; no bidderRequest.uspConsent.'); + logInfo('WILL NOT ADD CCPA info; no bidderRequest.uspConsent.'); } // this is for 2.2.1 // coppa compliance if (config.getConfig('coppa') === true) { - utils.deepSetValue(ozoneRequest, 'regs.coppa', 1); + deepSetValue(ozoneRequest, 'regs.coppa', 1); } // return the single request object OR the array: if (singleRequest) { - utils.logInfo('buildRequests starting to generate response for a single request'); + logInfo('buildRequests starting to generate response for a single request'); ozoneRequest.id = bidderRequest.auctionId; // Unique ID of the bid request, provided by the exchange. ozoneRequest.auctionId = bidderRequest.auctionId; // not sure if this should be here? ozoneRequest.imp = tosendtags; ozoneRequest.ext = extObj; ozoneRequest.source = {'tid': bidderRequest.auctionId}; // RTB 2.5 : tid is Transaction ID that must be common across all participants in this bid request (e.g., potentially multiple exchanges). - utils.deepSetValue(ozoneRequest, 'user.ext.eids', userExtEids); + deepSetValue(ozoneRequest, 'user.ext.eids', userExtEids); var ret = { method: 'POST', url: this.getAuctionUrl(), data: JSON.stringify(ozoneRequest), bidderRequest: bidderRequest }; - utils.logInfo('buildRequests request data for single = ', JSON.parse(JSON.stringify(ozoneRequest))); + logInfo('buildRequests request data for single = ', JSON.parse(JSON.stringify(ozoneRequest))); this.propertyBag.buildRequestsEnd = new Date().getTime(); - utils.logInfo(`buildRequests going to return for single at time ${this.propertyBag.buildRequestsEnd} (took ${this.propertyBag.buildRequestsEnd - this.propertyBag.buildRequestsStart}ms): `, ret); + logInfo(`buildRequests going to return for single at time ${this.propertyBag.buildRequestsEnd} (took ${this.propertyBag.buildRequestsEnd - this.propertyBag.buildRequestsStart}ms): `, ret); return ret; } // not single request - pull apart the tosendtags array & return an array of objects each containing one element in the imp array. let arrRet = tosendtags.map(imp => { - utils.logInfo('buildRequests starting to generate non-single response, working on imp : ', imp); + logInfo('buildRequests starting to generate non-single response, working on imp : ', imp); let ozoneRequestSingle = Object.assign({}, ozoneRequest); imp.ext[whitelabelBidder].pageAuctionId = bidderRequest['auctionId']; // make a note in the ext object of what the original auctionId was, in the bidderRequest object ozoneRequestSingle.id = imp.ext[whitelabelBidder].transactionId; // Unique ID of the bid request, provided by the exchange. @@ -413,8 +413,8 @@ export const spec = { ozoneRequestSingle.imp = [imp]; ozoneRequestSingle.ext = extObj; ozoneRequestSingle.source = {'tid': imp.ext[whitelabelBidder].transactionId}; - utils.deepSetValue(ozoneRequestSingle, 'user.ext.eids', userExtEids); - utils.logInfo('buildRequests RequestSingle (for non-single) = ', ozoneRequestSingle); + deepSetValue(ozoneRequestSingle, 'user.ext.eids', userExtEids); + logInfo('buildRequests RequestSingle (for non-single) = ', ozoneRequestSingle); return { method: 'POST', url: this.getAuctionUrl(), @@ -423,7 +423,7 @@ export const spec = { }; }); this.propertyBag.buildRequestsEnd = new Date().getTime(); - utils.logInfo(`buildRequests going to return for non-single at time ${this.propertyBag.buildRequestsEnd} (took ${this.propertyBag.buildRequestsEnd - this.propertyBag.buildRequestsStart}ms): `, arrRet); + logInfo(`buildRequests going to return for non-single at time ${this.propertyBag.buildRequestsEnd} (took ${this.propertyBag.buildRequestsEnd - this.propertyBag.buildRequestsStart}ms): `, arrRet); return arrRet; }, /** @@ -441,11 +441,11 @@ export const spec = { */ getFloorObjectForAuction(bidRequestRef) { const mediaTypesSizes = { - banner: utils.deepAccess(bidRequestRef, 'mediaTypes.banner.sizes', null), - video: utils.deepAccess(bidRequestRef, 'mediaTypes.video.playerSize', null), - native: utils.deepAccess(bidRequestRef, 'mediaTypes.native.image.sizes', null) + banner: deepAccess(bidRequestRef, 'mediaTypes.banner.sizes', null), + video: deepAccess(bidRequestRef, 'mediaTypes.video.playerSize', null), + native: deepAccess(bidRequestRef, 'mediaTypes.native.image.sizes', null) } - utils.logInfo('getFloorObjectForAuction mediaTypesSizes : ', mediaTypesSizes); + logInfo('getFloorObjectForAuction mediaTypesSizes : ', mediaTypesSizes); let ret = {}; if (mediaTypesSizes.banner) { ret.banner = bidRequestRef.getFloor({mediaType: 'banner', currency: 'USD', size: mediaTypesSizes.banner}); @@ -456,7 +456,7 @@ export const spec = { if (mediaTypesSizes.native) { ret.native = bidRequestRef.getFloor({mediaType: 'native', currency: 'USD', size: mediaTypesSizes.native}); } - utils.logInfo('getFloorObjectForAuction returning : ', JSON.parse(JSON.stringify(ret))); + logInfo('getFloorObjectForAuction returning : ', JSON.parse(JSON.stringify(ret))); return ret; }, /** @@ -474,8 +474,8 @@ export const spec = { let startTime = new Date().getTime(); let whitelabelBidder = this.propertyBag.whitelabel.bidder; // by default = ozone let whitelabelPrefix = this.propertyBag.whitelabel.keyPrefix; - utils.logInfo(`interpretResponse time: ${startTime} . Time between buildRequests done and interpretResponse start was ${startTime - this.propertyBag.buildRequestsEnd}ms`); - utils.logInfo(`serverResponse, request`, JSON.parse(JSON.stringify(serverResponse)), JSON.parse(JSON.stringify(request))); + logInfo(`interpretResponse time: ${startTime} . Time between buildRequests done and interpretResponse start was ${startTime - this.propertyBag.buildRequestsEnd}ms`); + logInfo(`serverResponse, request`, JSON.parse(JSON.stringify(serverResponse)), JSON.parse(JSON.stringify(request))); serverResponse = serverResponse.body || {}; // note that serverResponse.id value is the auction_id we might want to use for reporting reasons. if (!serverResponse.hasOwnProperty('seatbid')) { @@ -486,11 +486,11 @@ export const spec = { } let arrAllBids = []; let enhancedAdserverTargeting = this.getWhitelabelConfigItem('ozone.enhancedAdserverTargeting'); - utils.logInfo('enhancedAdserverTargeting', enhancedAdserverTargeting); + logInfo('enhancedAdserverTargeting', enhancedAdserverTargeting); if (typeof enhancedAdserverTargeting == 'undefined') { enhancedAdserverTargeting = true; } - utils.logInfo('enhancedAdserverTargeting', enhancedAdserverTargeting); + logInfo('enhancedAdserverTargeting', enhancedAdserverTargeting); // 2021-03-05 - comment this out for a build without adding adid to the response serverResponse.seatbid = injectAdIdsIntoAllBidResponses(serverResponse.seatbid); // we now make sure that each bid in the bidresponse has a unique (within page) adId attribute. @@ -499,38 +499,38 @@ export const spec = { let ozOmpFloorDollars = this.getWhitelabelConfigItem('ozone.oz_omp_floor'); // valid only if a dollar value (typeof == 'number') let addOzOmpFloorDollars = typeof ozOmpFloorDollars === 'number'; let ozWhitelistAdserverKeys = this.getWhitelabelConfigItem('ozone.oz_whitelist_adserver_keys'); - let useOzWhitelistAdserverKeys = utils.isArray(ozWhitelistAdserverKeys) && ozWhitelistAdserverKeys.length > 0; + let useOzWhitelistAdserverKeys = isArray(ozWhitelistAdserverKeys) && ozWhitelistAdserverKeys.length > 0; for (let i = 0; i < serverResponse.seatbid.length; i++) { let sb = serverResponse.seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { let thisRequestBid = this.getBidRequestForBidId(sb.bid[j].impid, request.bidderRequest.bids); - utils.logInfo(`seatbid:${i}, bid:${j} Going to set default w h for seatbid/bidRequest`, sb.bid[j], thisRequestBid); + logInfo(`seatbid:${i}, bid:${j} Going to set default w h for seatbid/bidRequest`, sb.bid[j], thisRequestBid); const {defaultWidth, defaultHeight} = defaultSize(thisRequestBid); let thisBid = ozoneAddStandardProperties(sb.bid[j], defaultWidth, defaultHeight); // prebid 4.0 compliance thisBid.meta = {advertiserDomains: thisBid.adomain || []}; let videoContext = null; let isVideo = false; - let bidType = utils.deepAccess(thisBid, 'ext.prebid.type'); - utils.logInfo(`this bid type is : ${bidType}`, j); + let bidType = deepAccess(thisBid, 'ext.prebid.type'); + logInfo(`this bid type is : ${bidType}`, j); if (bidType === VIDEO) { isVideo = true; videoContext = this.getVideoContextForBidId(thisBid.bidId, request.bidderRequest.bids); // should be instream or outstream (or null if error) if (videoContext === 'outstream') { - utils.logInfo('going to attach a renderer to OUTSTREAM video : ', j); + logInfo('going to attach a renderer to OUTSTREAM video : ', j); thisBid.renderer = newRenderer(thisBid.bidId); } else { - utils.logInfo('bid is not an outstream video, will not attach a renderer: ', j); + logInfo('bid is not an outstream video, will not attach a renderer: ', j); } } let adserverTargeting = {}; if (enhancedAdserverTargeting) { let allBidsForThisBidid = ozoneGetAllBidsForBidId(thisBid.bidId, serverResponse.seatbid); // add all the winning & non-winning bids for this bidId: - utils.logInfo('Going to iterate allBidsForThisBidId', allBidsForThisBidid); + logInfo('Going to iterate allBidsForThisBidId', allBidsForThisBidid); Object.keys(allBidsForThisBidid).forEach((bidderName, index, ar2) => { - utils.logInfo(`adding adserverTargeting for ${bidderName} for bidId ${thisBid.bidId}`); + logInfo(`adding adserverTargeting for ${bidderName} for bidId ${thisBid.bidId}`); // let bidderName = bidderNameWH.split('_')[0]; adserverTargeting[whitelabelPrefix + '_' + bidderName] = bidderName; adserverTargeting[whitelabelPrefix + '_' + bidderName + '_crid'] = String(allBidsForThisBidid[bidderName].crid); @@ -546,11 +546,11 @@ export const spec = { if (isVideo) { adserverTargeting[whitelabelPrefix + '_' + bidderName + '_vid'] = videoContext; // outstream or instream } - let flr = utils.deepAccess(allBidsForThisBidid[bidderName], `ext.bidder.${whitelabelBidder}.floor`, null); + let flr = deepAccess(allBidsForThisBidid[bidderName], `ext.bidder.${whitelabelBidder}.floor`, null); if (flr != null) { adserverTargeting[whitelabelPrefix + '_' + bidderName + '_flr'] = flr; } - let rid = utils.deepAccess(allBidsForThisBidid[bidderName], `ext.bidder.${whitelabelBidder}.ruleId`, null); + let rid = deepAccess(allBidsForThisBidid[bidderName], `ext.bidder.${whitelabelBidder}.ruleId`, null); if (rid != null) { adserverTargeting[whitelabelPrefix + '_' + bidderName + '_rid'] = rid; } @@ -560,9 +560,9 @@ export const spec = { }); } else { if (useOzWhitelistAdserverKeys) { - utils.logWarn(`You have set a whitelist of adserver keys but this will be ignored because ${whitelabelBidder}.enhancedAdserverTargeting is set to false. No per-bid keys will be sent to adserver.`); + logWarn(`You have set a whitelist of adserver keys but this will be ignored because ${whitelabelBidder}.enhancedAdserverTargeting is set to false. No per-bid keys will be sent to adserver.`); } else { - utils.logInfo(`${whitelabelBidder}.enhancedAdserverTargeting is set to false, so no per-bid keys will be sent to adserver.`); + logInfo(`${whitelabelBidder}.enhancedAdserverTargeting is set to false, so no per-bid keys will be sent to adserver.`); } } // also add in the winning bid, to be sent to dfp @@ -580,7 +580,7 @@ export const spec = { adserverTargeting[whitelabelPrefix + '_size'] = `${winningBid.width}x${winningBid.height}`; } if (useOzWhitelistAdserverKeys) { // delete any un-whitelisted keys - utils.logInfo('Going to filter out adserver targeting keys not in the whitelist: ', ozWhitelistAdserverKeys); + logInfo('Going to filter out adserver targeting keys not in the whitelist: ', ozWhitelistAdserverKeys); Object.keys(adserverTargeting).forEach(function(key) { if (ozWhitelistAdserverKeys.indexOf(key) === -1) { delete adserverTargeting[key]; } }); } thisBid.adserverTargeting = adserverTargeting; @@ -588,7 +588,7 @@ export const spec = { } } let endTime = new Date().getTime(); - utils.logInfo(`interpretResponse going to return at time ${endTime} (took ${endTime - startTime}ms) Time from buildRequests Start -> interpretRequests End = ${endTime - this.propertyBag.buildRequestsStart}ms`, arrAllBids); + logInfo(`interpretResponse going to return at time ${endTime} (took ${endTime - startTime}ms) Time from buildRequests Start -> interpretRequests End = ${endTime - this.propertyBag.buildRequestsStart}ms`, arrAllBids); return arrAllBids; }, /** @@ -616,7 +616,7 @@ export const spec = { var bidIds = []; for (let j = 0; j < sb.bid.length; j++) { var candidate = sb.bid[j]; - if (utils.contains(bidIds, candidate.impid)) { + if (contains(bidIds, candidate.impid)) { continue; // we've already fully assessed this impid, found the highest bid from this seat for it } bidIds.push(candidate.impid); @@ -634,7 +634,7 @@ export const spec = { // see http://prebid.org/dev-docs/bidder-adaptor.html#registering-user-syncs // us privacy: https://docs.prebid.org/dev-docs/modules/consentManagementUsp.html getUserSyncs(optionsType, serverResponse, gdprConsent, usPrivacy) { - utils.logInfo('getUserSyncs optionsType', optionsType, 'serverResponse', serverResponse, 'gdprConsent', gdprConsent, 'usPrivacy', usPrivacy, 'cookieSyncBag', this.cookieSyncBag); + logInfo('getUserSyncs optionsType', optionsType, 'serverResponse', serverResponse, 'gdprConsent', gdprConsent, 'usPrivacy', usPrivacy, 'cookieSyncBag', this.cookieSyncBag); if (!serverResponse || serverResponse.length === 0) { return []; } @@ -643,8 +643,8 @@ export const spec = { if (document.location.search.match(/pbjs_debug=true/)) { arrQueryString.push('pbjs_debug=true'); } - arrQueryString.push('gdpr=' + (utils.deepAccess(gdprConsent, 'gdprApplies', false) ? '1' : '0')); - arrQueryString.push('gdpr_consent=' + utils.deepAccess(gdprConsent, 'consentString', '')); + arrQueryString.push('gdpr=' + (deepAccess(gdprConsent, 'gdprApplies', false) ? '1' : '0')); + arrQueryString.push('gdpr_consent=' + deepAccess(gdprConsent, 'consentString', '')); arrQueryString.push('usp_consent=' + (usPrivacy || '')); // var objKeys = Object.getOwnPropertyNames(this.cookieSyncBag.userIdObject); // for (let idx in objKeys) { @@ -663,7 +663,7 @@ export const spec = { if (strQueryString.length > 0) { strQueryString = '?' + strQueryString; } - utils.logInfo('getUserSyncs going to return cookie sync url : ' + this.getCookieSyncUrl() + strQueryString); + logInfo('getUserSyncs going to return cookie sync url : ' + this.getCookieSyncUrl() + strQueryString); return [{ type: 'iframe', url: this.getCookieSyncUrl() + strQueryString @@ -693,7 +693,7 @@ export const spec = { getVideoContextForBidId(bidId, arrBids) { let requestBid = this.getBidRequestForBidId(bidId, arrBids); if (requestBid != null) { - return utils.deepAccess(requestBid, 'mediaTypes.video.context', 'unknown') + return deepAccess(requestBid, 'mediaTypes.video.context', 'unknown') } return null; }, @@ -715,37 +715,37 @@ export const spec = { if (typeof (bidRequest.userId[key]) == 'string') { ret[key] = bidRequest.userId[key]; } else if (typeof (bidRequest.userId[key]) == 'object') { - utils.logError(`WARNING: findAllUserIds had to use first key in user object to get value for bid.userId key: ${key}. Prebid adapter should be updated.`); + logError(`WARNING: findAllUserIds had to use first key in user object to get value for bid.userId key: ${key}. Prebid adapter should be updated.`); // fallback - get the value of the first key in the object; this is NOT desirable behaviour ret[key] = bidRequest.userId[key][Object.keys(bidRequest.userId[key])[0]]; // cannot use Object.values } else { - utils.logError(`failed to get string key value for userId : ${key}`); + logError(`failed to get string key value for userId : ${key}`); } } } - let lipbid = utils.deepAccess(bidRequest.userId, 'lipb.lipbid'); + let lipbid = deepAccess(bidRequest.userId, 'lipb.lipbid'); if (lipbid) { ret['lipb'] = {'lipbid': lipbid}; } - let id5id = utils.deepAccess(bidRequest.userId, 'id5id.uid'); + let id5id = deepAccess(bidRequest.userId, 'id5id.uid'); if (id5id) { ret['id5id'] = id5id; } - let parrableId = utils.deepAccess(bidRequest.userId, 'parrableId.eid'); + let parrableId = deepAccess(bidRequest.userId, 'parrableId.eid'); if (parrableId) { ret['parrableId'] = parrableId; } - let sharedid = utils.deepAccess(bidRequest.userId, 'sharedid.id'); + let sharedid = deepAccess(bidRequest.userId, 'sharedid.id'); if (sharedid) { ret['sharedid'] = sharedid; } - let sharedidthird = utils.deepAccess(bidRequest.userId, 'sharedid.third'); + let sharedidthird = deepAccess(bidRequest.userId, 'sharedid.third'); if (sharedidthird) { ret['sharedidthird'] = sharedidthird; } } if (!ret.hasOwnProperty('pubcid')) { - let pubcid = utils.deepAccess(bidRequest, 'crumbs.pubcid'); + let pubcid = deepAccess(bidRequest, 'crumbs.pubcid'); if (pubcid) { ret['pubcid'] = pubcid; // if built with old pubCommonId module } @@ -771,10 +771,10 @@ export const spec = { let arr = this.getGetParametersAsObject(); if (arr.hasOwnProperty(whitelabelPrefix + 'storedrequest')) { if (this.isValidPlacementId(arr[whitelabelPrefix + 'storedrequest'])) { - utils.logInfo(`using GET ${whitelabelPrefix}storedrequest ` + arr[whitelabelPrefix + 'storedrequest'] + ' to replace placementId'); + logInfo(`using GET ${whitelabelPrefix}storedrequest ` + arr[whitelabelPrefix + 'storedrequest'] + ' to replace placementId'); return arr[whitelabelPrefix + 'storedrequest']; } else { - utils.logError(`GET ${whitelabelPrefix}storedrequest FAILED VALIDATION - will not use it`); + logError(`GET ${whitelabelPrefix}storedrequest FAILED VALIDATION - will not use it`); } } return null; @@ -797,9 +797,9 @@ export const spec = { handleTTDId(eids, validBidRequests) { let ttdId = null; let adsrvrOrgId = config.getConfig('adsrvrOrgId'); - if (utils.isStr(utils.deepAccess(validBidRequests, '0.userId.tdid'))) { + if (isStr(deepAccess(validBidRequests, '0.userId.tdid'))) { ttdId = validBidRequests[0].userId.tdid; - } else if (adsrvrOrgId && utils.isStr(adsrvrOrgId.TDID)) { + } else if (adsrvrOrgId && isStr(adsrvrOrgId.TDID)) { ttdId = adsrvrOrgId.TDID; } if (ttdId !== null) { @@ -834,7 +834,7 @@ export const spec = { // if there is an ozone.oz_request = false then quit now. let ozRequest = this.getWhitelabelConfigItem('ozone.oz_request'); if (typeof ozRequest == 'boolean' && !ozRequest) { - utils.logWarn(`Will not allow auction : ${this.propertyBag.whitelabel.keyPrefix}one.${this.propertyBag.whitelabel.keyPrefix}_request is set to false`); + logWarn(`Will not allow auction : ${this.propertyBag.whitelabel.keyPrefix}one.${this.propertyBag.whitelabel.keyPrefix}_request is set to false`); return true; } return false; @@ -885,7 +885,7 @@ export const spec = { // handle ext separately, if it exists; we have probably built up an ext object already if (objConfig.hasOwnProperty('ext') && typeof objConfig.ext === 'object') { if (objConfig.hasOwnProperty('ext')) { - ret.ext = utils.mergeDeep(ret.ext, objConfig.ext); + ret.ext = mergeDeep(ret.ext, objConfig.ext); } else { ret.ext = objConfig.ext; } @@ -907,13 +907,13 @@ export const spec = { */ _addVideoDefaults(objRet, objConfig, addIfMissing) { // add inferred values & any default values we want. - let context = utils.deepAccess(objConfig, 'context'); + let context = deepAccess(objConfig, 'context'); if (context === 'outstream') { objRet.placement = 3; } else if (context === 'instream') { objRet.placement = 1; } - let skippable = utils.deepAccess(objConfig, 'skippable', null); + let skippable = deepAccess(objConfig, 'skippable', null); if (skippable == null) { if (addIfMissing && !objRet.hasOwnProperty('skip')) { objRet.skip = skippable ? 1 : 0; @@ -932,7 +932,7 @@ export const spec = { * @returns seatbid object */ export function injectAdIdsIntoAllBidResponses(seatbid) { - utils.logInfo('injectAdIdsIntoAllBidResponses', seatbid); + logInfo('injectAdIdsIntoAllBidResponses', seatbid); for (let i = 0; i < seatbid.length; i++) { let sb = seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { @@ -958,7 +958,7 @@ export function checkDeepArray(Arr) { export function defaultSize(thebidObj) { if (!thebidObj) { - utils.logInfo('defaultSize received empty bid obj! going to return fixed default size'); + logInfo('defaultSize received empty bid obj! going to return fixed default size'); return { 'defaultHeight': 250, 'defaultWidth': 300 @@ -1036,14 +1036,14 @@ export function getRoundedBid(price, mediaType) { let theConfigObject = getGranularityObject(mediaType, mediaTypeGranularity, strBuckets, objBuckets); let theConfigKey = getGranularityKeyName(mediaType, mediaTypeGranularity, strBuckets); - utils.logInfo('getRoundedBid. price:', price, 'mediaType:', mediaType, 'configkey:', theConfigKey, 'configObject:', theConfigObject, 'mediaTypeGranularity:', mediaTypeGranularity, 'strBuckets:', strBuckets); + logInfo('getRoundedBid. price:', price, 'mediaType:', mediaType, 'configkey:', theConfigKey, 'configObject:', theConfigObject, 'mediaTypeGranularity:', mediaTypeGranularity, 'strBuckets:', strBuckets); let priceStringsObj = getPriceBucketString( price, theConfigObject, config.getConfig('currency.granularityMultiplier') ); - utils.logInfo('priceStringsObj', priceStringsObj); + logInfo('priceStringsObj', priceStringsObj); // by default, without any custom granularity set, you get granularity name : 'medium' let granularityNamePriceStringsKeyMapping = { 'medium': 'med', @@ -1054,7 +1054,7 @@ export function getRoundedBid(price, mediaType) { }; if (granularityNamePriceStringsKeyMapping.hasOwnProperty(theConfigKey)) { let priceStringsKey = granularityNamePriceStringsKeyMapping[theConfigKey]; - utils.logInfo('getRoundedBid: looking for priceStringsKey:', priceStringsKey); + logInfo('getRoundedBid: looking for priceStringsKey:', priceStringsKey); return priceStringsObj[priceStringsKey]; } return priceStringsObj['auto']; @@ -1123,15 +1123,15 @@ export function getWidthAndHeightFromVideoObject(objVideo) { return null; } if (playerSize[0] && typeof playerSize[0] === 'object') { - utils.logInfo('getWidthAndHeightFromVideoObject found nested array inside playerSize.', playerSize[0]); + logInfo('getWidthAndHeightFromVideoObject found nested array inside playerSize.', playerSize[0]); playerSize = playerSize[0]; if (typeof playerSize[0] !== 'number' && typeof playerSize[0] !== 'string') { - utils.logInfo('getWidthAndHeightFromVideoObject found non-number/string type inside the INNER array in playerSize. This is totally wrong - cannot continue.', playerSize[0]); + logInfo('getWidthAndHeightFromVideoObject found non-number/string type inside the INNER array in playerSize. This is totally wrong - cannot continue.', playerSize[0]); return null; } } if (playerSize.length !== 2) { - utils.logInfo('getWidthAndHeightFromVideoObject found playerSize with length of ' + playerSize.length + '. This is totally wrong - cannot continue.'); + logInfo('getWidthAndHeightFromVideoObject found playerSize with length of ' + playerSize.length + '. This is totally wrong - cannot continue.'); return null; } return ({'w': playerSize[0], 'h': playerSize[1]}); @@ -1158,17 +1158,17 @@ export function playerSizeIsNestedArray(objVideo) { * @returns {*} */ function getPlayerSizeFromObject(objVideo) { - utils.logInfo('getPlayerSizeFromObject received object', objVideo); - let playerSize = utils.deepAccess(objVideo, 'playerSize'); + logInfo('getPlayerSizeFromObject received object', objVideo); + let playerSize = deepAccess(objVideo, 'playerSize'); if (!playerSize) { - playerSize = utils.deepAccess(objVideo, 'ext.playerSize'); + playerSize = deepAccess(objVideo, 'ext.playerSize'); } if (!playerSize) { - utils.logError('getPlayerSizeFromObject FAILED: no playerSize in video object or ext', objVideo); + logError('getPlayerSizeFromObject FAILED: no playerSize in video object or ext', objVideo); return null; } if (typeof playerSize !== 'object') { - utils.logError('getPlayerSizeFromObject FAILED: playerSize is not an object/array', objVideo); + logError('getPlayerSizeFromObject FAILED: playerSize is not an object/array', objVideo); return null; } return playerSize; @@ -1179,7 +1179,7 @@ function getPlayerSizeFromObject(objVideo) { */ function newRenderer(adUnitCode, rendererOptions = {}) { let isLoaded = window.ozoneVideo; - utils.logInfo(`newRenderer going to set loaded to ${isLoaded ? 'true' : 'false'}`); + logInfo(`newRenderer going to set loaded to ${isLoaded ? 'true' : 'false'}`); const renderer = Renderer.install({ url: spec.getRendererUrl(), config: rendererOptions, @@ -1189,12 +1189,12 @@ function newRenderer(adUnitCode, rendererOptions = {}) { try { renderer.setRender(outstreamRender); } catch (err) { - utils.logError('Prebid Error when calling setRender on renderer', JSON.parse(JSON.stringify(renderer)), err); + logError('Prebid Error when calling setRender on renderer', JSON.parse(JSON.stringify(renderer)), err); } return renderer; } function outstreamRender(bid) { - utils.logInfo('outstreamRender called. Going to push the call to window.ozoneVideo.outstreamRender(bid) bid =', JSON.parse(JSON.stringify(bid))); + logInfo('outstreamRender called. Going to push the call to window.ozoneVideo.outstreamRender(bid) bid =', JSON.parse(JSON.stringify(bid))); // push to render queue because ozoneVideo may not be loaded yet bid.renderer.push(() => { window.ozoneVideo.outstreamRender(bid); @@ -1202,4 +1202,4 @@ function outstreamRender(bid) { } registerBidder(spec); -utils.logInfo(`*BidAdapter ${OZONEVERSION} was loaded`); +logInfo(`*BidAdapter ${OZONEVERSION} was loaded`); diff --git a/modules/padsquadBidAdapter.js b/modules/padsquadBidAdapter.js index 24b1d5be3be..72449cf28be 100644 --- a/modules/padsquadBidAdapter.js +++ b/modules/padsquadBidAdapter.js @@ -1,5 +1,5 @@ +import { logInfo, deepAccess } 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 ENDPOINT_URL = 'https://x.padsquad.com/auction'; @@ -89,12 +89,12 @@ export const spec = { }) }) } else { - utils.logInfo('padsquad.interpretResponse :: no valid responses to interpret'); + logInfo('padsquad.interpretResponse :: no valid responses to interpret'); } return bidResponses; }, getUserSyncs: function (syncOptions, serverResponses) { - utils.logInfo('padsquad.getUserSyncs', 'syncOptions', syncOptions, 'serverResponses', serverResponses); + logInfo('padsquad.getUserSyncs', 'syncOptions', syncOptions, 'serverResponses', serverResponses); let syncs = []; if (!syncOptions.iframeEnabled && !syncOptions.pixelEnabled) { @@ -102,7 +102,7 @@ export const spec = { } serverResponses.forEach(resp => { - const userSync = utils.deepAccess(resp, 'body.ext.usersync'); + const userSync = deepAccess(resp, 'body.ext.usersync'); if (userSync) { let syncDetails = []; Object.keys(userSync).forEach(key => { diff --git a/modules/parrableIdSystem.js b/modules/parrableIdSystem.js index 1d74061e544..b1553bcb134 100644 --- a/modules/parrableIdSystem.js +++ b/modules/parrableIdSystem.js @@ -7,7 +7,7 @@ // ci trigger: 1 -import * as utils from '../src/utils.js' +import { timestamp, logError, logWarn, isEmpty, contains, inIframe, deepClone, isPlainObject } from '../src/utils.js'; import find from 'core-js-pure/features/array/find.js'; import { ajax } from '../src/ajax.js'; import { submodule } from '../src/hook.js'; @@ -26,7 +26,7 @@ const EXPIRE_COOKIE_DATE = 'Thu, 01 Jan 1970 00:00:00 GMT'; const storage = getStorageManager(PARRABLE_GVLID); function getExpirationDate() { - const oneYearFromNow = new Date(utils.timestamp() + ONE_YEAR_MS); + const oneYearFromNow = new Date(timestamp() + ONE_YEAR_MS); return oneYearFromNow.toGMTString(); } @@ -76,15 +76,15 @@ function serializeParrableId(parrableIdAndParams) { function isValidConfig(configParams) { if (!configParams) { - utils.logError('User ID - parrableId submodule requires configParams'); + logError('User ID - parrableId submodule requires configParams'); return false; } if (!configParams.partners && !configParams.partner) { - utils.logError('User ID - parrableId submodule requires partner list'); + logError('User ID - parrableId submodule requires partner list'); return false; } if (configParams.storage) { - utils.logWarn('User ID - parrableId submodule does not require a storage config'); + logWarn('User ID - parrableId submodule does not require a storage config'); } return true; } @@ -177,28 +177,28 @@ function shouldFilterImpression(configParams, parrableId) { } function isAllowed() { - if (utils.isEmpty(config.allowedZones) && - utils.isEmpty(config.allowedOffsets)) { + if (isEmpty(config.allowedZones) && + isEmpty(config.allowedOffsets)) { return true; } if (isZoneListed(config.allowedZones, zone)) { return true; } - if (utils.contains(config.allowedOffsets, offset)) { + if (contains(config.allowedOffsets, offset)) { return true; } return false; } function isBlocked() { - if (utils.isEmpty(config.blockedZones) && - utils.isEmpty(config.blockedOffsets)) { + if (isEmpty(config.blockedZones) && + isEmpty(config.blockedOffsets)) { return false; } if (isZoneListed(config.blockedZones, zone)) { return true; } - if (utils.contains(config.blockedOffsets, offset)) { + if (contains(config.blockedOffsets, offset)) { return true; } return false; @@ -246,7 +246,7 @@ function fetchId(configParams, gdprConsentData) { trackers, url: refererInfo.referer, prebidVersion: '$prebid.version$', - isIframe: utils.inIframe(), + isIframe: inIframe(), tpcSupport }; @@ -276,7 +276,7 @@ function fetchId(configParams, gdprConsentData) { const callback = function (cb) { const callbacks = { success: response => { - let newParrableId = parrableId ? utils.deepClone(parrableId) : {}; + let newParrableId = parrableId ? deepClone(parrableId) : {}; let newParams = {}; if (response) { try { @@ -301,18 +301,18 @@ function fetchId(configParams, gdprConsentData) { } } } catch (error) { - utils.logError(error); + logError(error); cb(); } writeCookie({ ...newParrableId, ...newParams }); cb(newParrableId); } else { - utils.logError('parrableId: ID fetch returned an empty result'); + logError('parrableId: ID fetch returned an empty result'); cb(); } }, error: error => { - utils.logError(`parrableId: ID fetch encountered an error`, error); + logError(`parrableId: ID fetch encountered an error`, error); cb(); } }; @@ -350,7 +350,7 @@ export const parrableIdSubmodule = { * @return {(Object|undefined} */ decode(parrableId) { - if (parrableId && utils.isPlainObject(parrableId)) { + if (parrableId && isPlainObject(parrableId)) { return { parrableId }; } return undefined; diff --git a/modules/pixfutureBidAdapter.js b/modules/pixfutureBidAdapter.js index e5422f36358..41e561a6f83 100644 --- a/modules/pixfutureBidAdapter.js +++ b/modules/pixfutureBidAdapter.js @@ -1,9 +1,9 @@ +import { convertCamelToUnderscore, isArray, isNumber, isPlainObject, deepAccess, isEmpty, transformBidderParamKeywords, isFn } from '../src/utils.js'; import { registerBidder } from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; import { BANNER } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; import includes from 'core-js-pure/features/array/includes.js'; -import * as utils from '../src/utils.js'; import { auctionManager } from '../src/auctionManager.js'; import find from 'core-js-pure/features/array/find.js'; @@ -47,13 +47,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); } }); @@ -93,14 +93,14 @@ export const spec = { if (validBidRequests[0].userId) { let eids = []; - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.flocId.id`), 'chrome.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.criteoId`), 'criteo.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.unifiedId`), 'thetradedesk.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.id5Id`), 'id5.io', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.sharedId`), 'thetradedesk.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.identityLink`), 'liveramp.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.liveIntentId`), 'liveintent.com', null); - addUserId(eids, utils.deepAccess(validBidRequests[0], `userId.fabrickId`), 'home.neustar', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.flocId.id`), 'chrome.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.criteoId`), 'criteo.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.unifiedId`), 'thetradedesk.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.id5Id`), 'id5.io', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.sharedId`), 'thetradedesk.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.identityLink`), 'liveramp.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.liveIntentId`), 'liveintent.com', null); + addUserId(eids, deepAccess(validBidRequests[0], `userId.fabrickId`), 'home.neustar', null); if (eids.length) { payload.eids = eids; @@ -223,8 +223,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); @@ -232,7 +232,7 @@ 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; } @@ -241,7 +241,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; } @@ -276,8 +276,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); @@ -295,7 +295,7 @@ function transformSizes(requestSizes) { } function getBidFloor(bid) { - if (!utils.isFn(bid.getFloor)) { + if (!isFn(bid.getFloor)) { return (bid.params.reserve) ? bid.params.reserve : null; } @@ -304,7 +304,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; @@ -317,7 +317,7 @@ function deleteValues(keyPairObj) { } function isPopulatedArray(arr) { - return !!(utils.isArray(arr) && arr.length > 0); + return !!(isArray(arr) && arr.length > 0); } registerBidder(spec); diff --git a/modules/prebidmanagerAnalyticsAdapter.js b/modules/prebidmanagerAnalyticsAdapter.js index b9a7d79f991..a1a0a636e3c 100644 --- a/modules/prebidmanagerAnalyticsAdapter.js +++ b/modules/prebidmanagerAnalyticsAdapter.js @@ -1,3 +1,4 @@ +import { generateUUID, getParameterByName, logError, parseUrl, logInfo } from '../src/utils.js'; import {ajaxBuilder} from '../src/ajax.js'; import adapter from '../src/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; @@ -11,13 +12,12 @@ const DEFAULT_EVENT_URL = 'https://endpoint.prebidmanager.com/endpoint' const analyticsType = 'endpoint'; const analyticsName = 'Prebid Manager Analytics: '; -var utils = require('../src/utils.js'); var CONSTANTS = require('../src/constants.json'); let ajax = ajaxBuilder(0); var _VERSION = 1; var initOptions = null; -var _pageViewId = utils.generateUUID(); +var _pageViewId = generateUUID(); var _startAuction = 0; var _bidRequestTimeout = 0; let flushInterval; @@ -76,7 +76,7 @@ function collectUtmTagData() { let pmUtmTags = {}; try { utmTags.forEach(function (utmKey) { - let utmValue = utils.getParameterByName(utmKey); + let utmValue = getParameterByName(utmKey); if (utmValue !== '') { newUtm = true; } @@ -95,7 +95,7 @@ function collectUtmTagData() { }); } } catch (e) { - utils.logError(`${analyticsName}Error`, e); + logError(`${analyticsName}Error`, e); pmUtmTags['error_utm'] = 1; } return pmUtmTags; @@ -106,7 +106,7 @@ function collectPageInfo() { domain: window.location.hostname, } if (document.referrer) { - pageInfo.referrerDomain = utils.parseUrl(document.referrer).hostname; + pageInfo.referrerDomain = parseUrl(document.referrer).hostname; } return pageInfo; } @@ -128,7 +128,7 @@ function flush() { ajax( initOptions.url, - () => utils.logInfo(`${analyticsName} sent events batch`), + () => logInfo(`${analyticsName} sent events batch`), _VERSION + ':' + JSON.stringify(data), { contentType: 'text/plain', @@ -215,7 +215,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 === CONSTANTS.EVENTS.AUCTION_END) { flush(); diff --git a/modules/priceFloors.js b/modules/priceFloors.js index 5f7a39e0784..b55638c1a5c 100644 --- a/modules/priceFloors.js +++ b/modules/priceFloors.js @@ -1,6 +1,6 @@ +import { parseUrl, deepAccess, parseGPTSingleSizeArray, getGptSlotInfoForAdUnitCode, deepSetValue, logWarn, deepClone, getParameterByName, generateUUID, logError, logInfo, isNumber, pick, debugTurnedOn } from '../src/utils.js'; import { getGlobal } from '../src/prebidGlobal.js'; import { config } from '../src/config.js'; -import * as utils from '../src/utils.js'; import { ajaxBuilder } from '../src/ajax.js'; import events from '../src/events.js'; import CONSTANTS from '../src/constants.json'; @@ -60,13 +60,13 @@ function roundUp(number, precision) { let referrerHostname; function getHostNameFromReferer(referer) { - referrerHostname = utils.parseUrl(referer, {noDecodeWholeURL: true}).hostname; + referrerHostname = parseUrl(referer, {noDecodeWholeURL: true}).hostname; return referrerHostname; } // First look into bidRequest! function getGptSlotFromBidRequest(bidRequest) { - const isGam = utils.deepAccess(bidRequest, 'ortb2Imp.ext.data.adserver.name') === 'gam'; + const isGam = deepAccess(bidRequest, 'ortb2Imp.ext.data.adserver.name') === 'gam'; return isGam && bidRequest.ortb2Imp.ext.data.adserver.adslot; } @@ -74,9 +74,9 @@ function getGptSlotFromBidRequest(bidRequest) { * @summary floor field types with their matching functions to resolve the actual matched value */ export let fieldMatchingFunctions = { - 'size': (bidRequest, bidResponse) => utils.parseGPTSingleSizeArray(bidResponse.size) || '*', + 'size': (bidRequest, bidResponse) => parseGPTSingleSizeArray(bidResponse.size) || '*', 'mediaType': (bidRequest, bidResponse) => bidResponse.mediaType || 'banner', - 'gptSlot': (bidRequest, bidResponse) => getGptSlotFromBidRequest(bidRequest) || utils.getGptSlotInfoForAdUnitCode(bidRequest.adUnitCode).gptSlot, + 'gptSlot': (bidRequest, bidResponse) => getGptSlotFromBidRequest(bidRequest) || getGptSlotInfoForAdUnitCode(bidRequest.adUnitCode).gptSlot, 'domain': (bidRequest, bidResponse) => referrerHostname || getHostNameFromReferer(getRefererInfo().referer), 'adUnitCode': (bidRequest, bidResponse) => bidRequest.adUnitCode } @@ -101,17 +101,17 @@ function enumeratePossibleFieldValues(floorFields, bidObject, responseObject) { * Generates all possible rule matches and picks the first matching one. */ export function getFirstMatchingFloor(floorData, bidObject, responseObject = {}) { - let fieldValues = enumeratePossibleFieldValues(utils.deepAccess(floorData, 'schema.fields') || [], bidObject, responseObject); + let fieldValues = enumeratePossibleFieldValues(deepAccess(floorData, 'schema.fields') || [], bidObject, responseObject); if (!fieldValues.length) return { matchingFloor: floorData.default }; // look to see if a request for this context was made already let matchingInput = fieldValues.map(field => field[0]).join('-'); // if we already have gotten the matching rule from this matching input then use it! No need to look again - let previousMatch = utils.deepAccess(floorData, `matchingInputs.${matchingInput}`); + let previousMatch = deepAccess(floorData, `matchingInputs.${matchingInput}`); if (previousMatch) { return {...previousMatch}; } - let allPossibleMatches = generatePossibleEnumerations(fieldValues, utils.deepAccess(floorData, 'schema.delimiter') || '|'); + let allPossibleMatches = generatePossibleEnumerations(fieldValues, deepAccess(floorData, 'schema.delimiter') || '|'); let matchingRule = find(allPossibleMatches, hashValue => floorData.values.hasOwnProperty(hashValue)); let matchingData = { @@ -122,7 +122,7 @@ export function getFirstMatchingFloor(floorData, bidObject, responseObject = {}) }; matchingData.matchingFloor = Math.max(matchingData.floorMin, matchingData.floorRuleValue); // save for later lookup if needed - utils.deepSetValue(floorData, `matchingInputs.${matchingInput}`, {...matchingData}); + deepSetValue(floorData, `matchingInputs.${matchingInput}`, {...matchingData}); return matchingData; } @@ -147,7 +147,7 @@ function generatePossibleEnumerations(arrayOfFields, delimiter) { * @summary If a the input bidder has a registered cpmadjustment it returns the input CPM after being adjusted */ export function getBiddersCpmAdjustment(bidderName, inputCpm, bid = {}) { - const adjustmentFunction = utils.deepAccess(getGlobal(), `bidderSettings.${bidderName}.bidCpmAdjustment`) || utils.deepAccess(getGlobal(), 'bidderSettings.standard.bidCpmAdjustment'); + const adjustmentFunction = deepAccess(getGlobal(), `bidderSettings.${bidderName}.bidCpmAdjustment`) || deepAccess(getGlobal(), 'bidderSettings.standard.bidCpmAdjustment'); if (adjustmentFunction) { return parseFloat(adjustmentFunction(inputCpm, {...bid, cpm: inputCpm})); } @@ -167,9 +167,9 @@ export function calculateAdjustedFloor(oldFloor, newFloor) { * @summary gets the prebid set sizes depending on the input mediaType */ const getMediaTypesSizes = { - banner: (bid) => utils.deepAccess(bid, 'mediaTypes.banner.sizes') || [], - video: (bid) => utils.deepAccess(bid, 'mediaTypes.video.playerSize') || [], - native: (bid) => utils.deepAccess(bid, 'mediaTypes.native.image.sizes') ? [utils.deepAccess(bid, 'mediaTypes.native.image.sizes')] : [] + banner: (bid) => deepAccess(bid, 'mediaTypes.banner.sizes') || [], + video: (bid) => deepAccess(bid, 'mediaTypes.video.playerSize') || [], + native: (bid) => deepAccess(bid, 'mediaTypes.native.image.sizes') ? [deepAccess(bid, 'mediaTypes.native.image.sizes')] : [] } /** @@ -208,7 +208,7 @@ export function getFloor(requestParams = {currency: 'USD', mediaType: '*', size: try { floorInfo.matchingFloor = getGlobal().convertCurrency(floorInfo.matchingFloor, floorData.data.currency, currency); } catch (err) { - utils.logWarn(`${MODULE_NAME}: Unable to get currency conversion for getFloor for bidder ${bidRequest.bidder}. You must have currency module enabled with defaultRates in your currency config`); + logWarn(`${MODULE_NAME}: Unable to get currency conversion for getFloor for bidder ${bidRequest.bidder}. You must have currency module enabled with defaultRates in your currency config`); // since we were unable to convert to the bidders requested currency, we send back just the actual floors currency to them currency = floorData.data.currency; } @@ -233,7 +233,7 @@ export function getFloor(requestParams = {currency: 'USD', mediaType: '*', size: * @summary Takes a floorsData object and converts it into a hash map with appropriate keys */ export function getFloorsDataForAuction(floorData, adUnitCode) { - let auctionFloorData = utils.deepClone(floorData); + let auctionFloorData = deepClone(floorData); auctionFloorData.schema.delimiter = floorData.schema.delimiter || '|'; auctionFloorData.values = normalizeRulesForAuction(auctionFloorData, adUnitCode); // default the currency to USD if not passed in @@ -296,10 +296,10 @@ export function updateAdUnitsForAuction(adUnits, floorData, auctionId) { skipped: floorData.skipped, skipRate: floorData.skipRate, floorMin: floorData.floorMin, - modelVersion: utils.deepAccess(floorData, 'data.modelVersion'), - modelWeight: utils.deepAccess(floorData, 'data.modelWeight'), - modelTimestamp: utils.deepAccess(floorData, 'data.modelTimestamp'), - location: utils.deepAccess(floorData, 'data.location', 'noData'), + modelVersion: deepAccess(floorData, 'data.modelVersion'), + modelWeight: deepAccess(floorData, 'data.modelWeight'), + modelTimestamp: deepAccess(floorData, 'data.modelTimestamp'), + location: deepAccess(floorData, 'data.location', 'noData'), floorProvider: floorData.floorProvider, fetchStatus: _floorsConfig.fetchStatus }; @@ -323,27 +323,27 @@ export function pickRandomModel(modelGroups, weightSum) { * @summary Updates the adUnits accordingly and returns the necessary floorsData for the current auction */ export function createFloorsDataForAuction(adUnits, auctionId) { - let resolvedFloorsData = utils.deepClone(_floorsConfig); + let resolvedFloorsData = deepClone(_floorsConfig); // if using schema 2 pick a model here: - if (utils.deepAccess(resolvedFloorsData, 'data.floorsSchemaVersion') === 2) { + if (deepAccess(resolvedFloorsData, 'data.floorsSchemaVersion') === 2) { // merge the models specific stuff into the top level data settings (now it looks like floorsSchemaVersion 1!) let { modelGroups, ...rest } = resolvedFloorsData.data; resolvedFloorsData.data = Object.assign(rest, pickRandomModel(modelGroups, rest.modelWeightSum)); } // if we do not have a floors data set, we will try to use data set on adUnits - let useAdUnitData = Object.keys(utils.deepAccess(resolvedFloorsData, 'data.values') || {}).length === 0; + let useAdUnitData = Object.keys(deepAccess(resolvedFloorsData, 'data.values') || {}).length === 0; if (useAdUnitData) { resolvedFloorsData.data = getFloorDataFromAdUnits(adUnits); } else { resolvedFloorsData.data = getFloorsDataForAuction(resolvedFloorsData.data); } // if we still do not have a valid floor data then floors is not on for this auction, so skip - if (Object.keys(utils.deepAccess(resolvedFloorsData, 'data.values') || {}).length === 0) { + if (Object.keys(deepAccess(resolvedFloorsData, 'data.values') || {}).length === 0) { resolvedFloorsData.skipped = true; } else { // determine the skip rate now - const auctionSkipRate = utils.getParameterByName('pbjs_skipRate') || resolvedFloorsData.skipRate; + const auctionSkipRate = getParameterByName('pbjs_skipRate') || resolvedFloorsData.skipRate; const isSkipped = Math.random() * 100 < parseFloat(auctionSkipRate); resolvedFloorsData.skipped = isSkipped; } @@ -364,7 +364,7 @@ export function continueAuction(hookConfig) { _delayedAuctions = _delayedAuctions.filter(auctionConfig => auctionConfig.timer !== hookConfig.timer); // We need to know the auctionId at this time. So we will use the passed in one or generate and set it ourselves - hookConfig.reqBidsConfigObj.auctionId = hookConfig.reqBidsConfigObj.auctionId || utils.generateUUID(); + hookConfig.reqBidsConfigObj.auctionId = hookConfig.reqBidsConfigObj.auctionId || generateUUID(); // now we do what we need to with adUnits and save the data object to be used for getFloor and enforcement calls _floorDataForAuction[hookConfig.reqBidsConfigObj.auctionId] = createFloorsDataForAuction(hookConfig.reqBidsConfigObj.adUnits || getGlobal().adUnits, hookConfig.reqBidsConfigObj.auctionId); @@ -378,7 +378,7 @@ function validateSchemaFields(fields) { if (Array.isArray(fields) && fields.length > 0 && fields.every(field => allowedFields.indexOf(field) !== -1)) { return true; } - utils.logError(`${MODULE_NAME}: Fields recieved do not match allowed fields`); + logError(`${MODULE_NAME}: Fields recieved do not match allowed fields`); return false; } @@ -406,7 +406,7 @@ function validateRules(floorsData, numFields, delimiter) { function modelIsValid(model) { // schema.fields has only allowed attributes - if (!validateSchemaFields(utils.deepAccess(model, 'schema.fields'))) { + if (!validateSchemaFields(deepAccess(model, 'schema.fields'))) { return false; } return validateRules(model, model.schema.fields.length, model.schema.delimiter || '|') @@ -446,7 +446,7 @@ export function isFloorsDataValid(floorsData) { } floorsData.floorsSchemaVersion = floorsData.floorsSchemaVersion || 1; if (typeof floorsSchemaValidation[floorsData.floorsSchemaVersion] !== 'function') { - utils.logError(`${MODULE_NAME}: Unknown floorsSchemaVersion: `, floorsData.floorsSchemaVersion); + logError(`${MODULE_NAME}: Unknown floorsSchemaVersion: `, floorsData.floorsSchemaVersion); return false; } return floorsSchemaValidation[floorsData.floorsSchemaVersion](floorsData); @@ -457,13 +457,13 @@ export function isFloorsDataValid(floorsData) { */ export function parseFloorData(floorsData, location) { if (floorsData && typeof floorsData === 'object' && isFloorsDataValid(floorsData)) { - utils.logInfo(`${MODULE_NAME}: A ${location} set the auction floor data set to `, floorsData); + logInfo(`${MODULE_NAME}: A ${location} set the auction floor data set to `, floorsData); return { ...floorsData, location }; } - utils.logError(`${MODULE_NAME}: The floors data did not contain correct values`, floorsData); + logError(`${MODULE_NAME}: The floors data did not contain correct values`, floorsData); } /** @@ -484,7 +484,7 @@ export function requestBidsHook(fn, reqBidsConfigObj) { // If auction delay > 0 AND we are fetching -> Then wait until it finishes if (_floorsConfig.auctionDelay > 0 && fetching) { hookConfig.timer = setTimeout(() => { - utils.logWarn(`${MODULE_NAME}: Fetch attempt did not return in time for auction`); + logWarn(`${MODULE_NAME}: Fetch attempt did not return in time for auction`); _floorsConfig.fetchStatus = 'timeout'; continueAuction(hookConfig); }, _floorsConfig.auctionDelay); @@ -526,7 +526,7 @@ export function handleFetchResponse(fetchResponse) { // set .data to it _floorsConfig.data = fetchData; // set skipRate override if necessary - _floorsConfig.skipRate = utils.isNumber(fetchData.skipRate) ? fetchData.skipRate : _floorsConfig.skipRate; + _floorsConfig.skipRate = isNumber(fetchData.skipRate) ? fetchData.skipRate : _floorsConfig.skipRate; _floorsConfig.floorProvider = fetchData.floorProvider || _floorsConfig.floorProvider; } @@ -537,7 +537,7 @@ export function handleFetchResponse(fetchResponse) { function handleFetchError(status) { fetching = false; _floorsConfig.fetchStatus = 'error'; - utils.logError(`${MODULE_NAME}: Fetch errored with: `, status); + logError(`${MODULE_NAME}: Fetch errored with: `, status); // if any auctions are waiting for fetch to finish, we need to continue them! resumeDelayedAuctions(); @@ -553,13 +553,13 @@ export function generateAndHandleFetch(floorEndpoint) { // default to GET and we only support GET for now let requestMethod = floorEndpoint.method || 'GET'; if (requestMethod !== 'GET') { - utils.logError(`${MODULE_NAME}: 'GET' is the only request method supported at this time!`); + logError(`${MODULE_NAME}: 'GET' is the only request method supported at this time!`); } else { ajax(floorEndpoint.url, { success: handleFetchResponse, error: handleFetchError }, null, { method: 'GET' }); fetching = true; } } else if (fetching) { - utils.logWarn(`${MODULE_NAME}: A fetch is already occuring. Skipping.`); + logWarn(`${MODULE_NAME}: A fetch is already occuring. Skipping.`); } } @@ -580,14 +580,14 @@ function addFieldOverrides(overrides) { * @summary This is the function which controls what happens during a pbjs.setConfig({...floors: {}}) is called */ export function handleSetFloorsConfig(config) { - _floorsConfig = utils.pick(config, [ + _floorsConfig = pick(config, [ 'floorMin', 'enabled', enabled => enabled !== false, // defaults to true 'auctionDelay', auctionDelay => auctionDelay || 0, - 'floorProvider', floorProvider => utils.deepAccess(config, 'data.floorProvider', floorProvider), + 'floorProvider', floorProvider => deepAccess(config, 'data.floorProvider', floorProvider), 'endpoint', endpoint => endpoint || {}, - 'skipRate', () => !isNaN(utils.deepAccess(config, 'data.skipRate')) ? config.data.skipRate : config.skipRate || 0, - 'enforcement', enforcement => utils.pick(enforcement || {}, [ + 'skipRate', () => !isNaN(deepAccess(config, 'data.skipRate')) ? config.data.skipRate : config.skipRate || 0, + 'enforcement', enforcement => pick(enforcement || {}, [ 'enforceJS', enforceJS => enforceJS !== false, // defaults to true 'enforcePBS', enforcePBS => enforcePBS === true, // defaults to false 'floorDeals', floorDeals => floorDeals === true, // defaults to false @@ -613,11 +613,11 @@ export function handleSetFloorsConfig(config) { getGlobal().requestBids.before(requestBidsHook, 50); // if user has debug on then we want to allow the debugging module to run before this, assuming they are testing priceFloors // debugging is currently set at 5 priority - getHook('addBidResponse').before(addBidResponseHook, utils.debugTurnedOn() ? 4 : 50); + getHook('addBidResponse').before(addBidResponseHook, debugTurnedOn() ? 4 : 50); addedFloorsHook = true; } } else { - utils.logInfo(`${MODULE_NAME}: Turning off module`); + logInfo(`${MODULE_NAME}: Turning off module`); _floorsConfig = {}; _floorDataForAuction = {}; @@ -653,8 +653,8 @@ function addFloorDataToBid(floorData, floorInfo, bid, adjustedCpm) { * @summary takes the enforcement flags and the bid itself and determines if it should be floored */ function shouldFloorBid(floorData, floorInfo, bid) { - let enforceJS = utils.deepAccess(floorData, 'enforcement.enforceJS') !== false; - let shouldFloorDeal = utils.deepAccess(floorData, 'enforcement.floorDeals') === true || !bid.dealId; + let enforceJS = deepAccess(floorData, 'enforcement.enforceJS') !== false; + let shouldFloorDeal = deepAccess(floorData, 'enforcement.floorDeals') === true || !bid.dealId; let bidBelowFloor = bid.floorData.cpmAfterAdjustments < floorInfo.matchingFloor; return enforceJS && (bidBelowFloor && shouldFloorDeal); } @@ -675,7 +675,7 @@ export function addBidResponseHook(fn, adUnitCode, bid) { let floorInfo = getFirstMatchingFloor(floorData.data, {...matchingBidRequest}, {...bid, size: [bid.width, bid.height]}); if (!floorInfo.matchingFloor) { - utils.logWarn(`${MODULE_NAME}: unable to determine a matching price floor for bidResponse`, bid); + logWarn(`${MODULE_NAME}: unable to determine a matching price floor for bidResponse`, bid); return fn.call(this, adUnitCode, bid); } @@ -691,7 +691,7 @@ export function addBidResponseHook(fn, adUnitCode, bid) { try { adjustedCpm = getGlobal().convertCurrency(bid.cpm, bidResponseCurrency.toUpperCase(), floorCurrency); } catch (err) { - utils.logError(`${MODULE_NAME}: Unable do get currency conversion for bidResponse to Floor Currency. Do you have Currency module enabled? ${bid}`); + logError(`${MODULE_NAME}: Unable do get currency conversion for bidResponse to Floor Currency. Do you have Currency module enabled? ${bid}`); return fn.call(this, adUnitCode, bid); } } @@ -707,7 +707,7 @@ export function addBidResponseHook(fn, adUnitCode, bid) { // bid fails floor -> throw it out // create basic bid no-bid with necessary data fro analytics adapters let flooredBid = createBid(CONSTANTS.STATUS.NO_BID, matchingBidRequest); - Object.assign(flooredBid, utils.pick(bid, [ + Object.assign(flooredBid, pick(bid, [ 'floorData', 'width', 'height', @@ -720,7 +720,7 @@ export function addBidResponseHook(fn, adUnitCode, bid) { flooredBid.status = CONSTANTS.BID_STATUS.BID_REJECTED; // if floor not met update bid with 0 cpm so it is not included downstream and marked as no-bid flooredBid.cpm = 0; - utils.logWarn(`${MODULE_NAME}: ${flooredBid.bidderCode}'s Bid Response for ${adUnitCode} was rejected due to floor not met`, bid); + logWarn(`${MODULE_NAME}: ${flooredBid.bidderCode}'s Bid Response for ${adUnitCode} was rejected due to floor not met`, bid); return fn.call(this, adUnitCode, flooredBid); } return fn.call(this, adUnitCode, bid);