From 9a180dbfc707978271c880cc24fa3420e2e8615f Mon Sep 17 00:00:00 2001 From: olafbuitelaar Date: Wed, 29 Mar 2023 17:34:55 +0200 Subject: [PATCH] CORE: allow to disable setting the pbjs global variable (#9568) * allow to disable settings the pbjs global variable * factored out all references to $$PREBID_GLOBAL$$ to use getGlobal instead updated the babel module, to directly call the getGlobal function removed eslint global exception, and added them as local exceptions * fix comments * make module use getGlobal * Isolate `installedModules` management from module namespaces * Use relative import paths in autogenerated code for `installedModules` * Remove $$PREBID_GLOBAL$$ macro ref from rubicon adapter * Revert "Remove $$PREBID_GLOBAL$$ macro ref from rubicon adapter" This reverts commit 16e25ddc536d0b96aae0b13130816812347e0128. --------- Co-authored-by: Demetrio Girardi --- .eslintrc.js | 1 - modules/addefendBidAdapter.js | 3 +- modules/adxcgAnalyticsAdapter.js | 3 +- modules/atsAnalyticsAdapter.js | 3 +- modules/consentManagement.js | 3 +- modules/consentManagementGpp.js | 3 +- modules/express.js | 12 +-- modules/id5AnalyticsAdapter.js | 3 +- modules/mabidderBidAdapter.js | 4 +- modules/marsmediaAnalyticsAdapter.js | 3 +- modules/medianetAnalyticsAdapter.js | 7 +- modules/medianetBidAdapter.js | 11 +-- modules/orbidderBidAdapter.js | 3 +- modules/pixfutureBidAdapter.js | 3 +- modules/pubCommonId.js | 5 +- modules/pubxaiAnalyticsAdapter.js | 3 +- modules/rivrAnalyticsAdapter.js | 3 +- modules/snigelBidAdapter.js | 3 +- modules/tappxBidAdapter.js | 3 +- modules/terceptAnalyticsAdapter.js | 3 +- modules/yuktamediaAnalyticsAdapter.js | 3 +- package.json | 1 + plugins/pbjsGlobals.js | 21 +++-- src/Renderer.js | 5 +- src/auction.js | 5 +- src/prebid.js | 120 +++++++++++++------------- src/prebidGlobal.js | 20 +++-- src/utils.js | 5 +- 28 files changed, 156 insertions(+), 106 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 06a5e81d9f5..fc3ad3afe66 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -19,7 +19,6 @@ module.exports = { 'import' ], globals: { - '$$PREBID_GLOBAL$$': false, 'BROWSERSTACK_USERNAME': false, 'BROWSERSTACK_KEY': false, 'FEATURES': 'readonly', diff --git a/modules/addefendBidAdapter.js b/modules/addefendBidAdapter.js index f0a6852b084..d73c25935ee 100644 --- a/modules/addefendBidAdapter.js +++ b/modules/addefendBidAdapter.js @@ -1,4 +1,5 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const BIDDER_CODE = 'addefend'; @@ -16,7 +17,7 @@ export const spec = { }, buildRequests: function(validBidRequests, bidderRequest) { let bid = { - v: $$PREBID_GLOBAL$$.version, + v: getGlobal().version, auctionId: false, pageId: false, gdpr_applies: bidderRequest.gdprConsent && bidderRequest.gdprConsent.gdprApplies ? bidderRequest.gdprConsent.gdprApplies : 'true', diff --git a/modules/adxcgAnalyticsAdapter.js b/modules/adxcgAnalyticsAdapter.js index f3bb1270334..21b6c1be783 100644 --- a/modules/adxcgAnalyticsAdapter.js +++ b/modules/adxcgAnalyticsAdapter.js @@ -3,6 +3,7 @@ import { ajax } from '../src/ajax.js'; import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; +import {getGlobal} from '../src/prebidGlobal.js'; /** * Analytics adapter from adxcg.com @@ -122,7 +123,7 @@ function send (data) { ats: adxcgAnalyticsAdapter.context.auctionTimestamp, aav: adxcgAnalyticsVersion, iob: intersectionObserverAvailable(window) ? '1' : '0', - pbv: $$PREBID_GLOBAL$$.version, + pbv: getGlobal().version, sz: window.screen.width + 'x' + window.screen.height } }); diff --git a/modules/atsAnalyticsAdapter.js b/modules/atsAnalyticsAdapter.js index 0c0227ea34a..448969c6f29 100644 --- a/modules/atsAnalyticsAdapter.js +++ b/modules/atsAnalyticsAdapter.js @@ -4,6 +4,7 @@ import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; +import {getGlobal} from '../src/prebidGlobal.js'; export const storage = getStorageManager(); @@ -352,7 +353,7 @@ atsAnalyticsAdapter.callHandler = function (evtype, args) { let bidWonTimeout = atsAnalyticsAdapter.context.bidWonTimeout ? atsAnalyticsAdapter.context.bidWonTimeout : 2000; let events = []; setTimeout(() => { - let winningBids = $$PREBID_GLOBAL$$.getAllWinningBids(); + let winningBids = getGlobal().getAllWinningBids(); logInfo('ATS Analytics - winning bids: ', winningBids) // prepare format data for sending to analytics endpoint if (handlerRequest.length) { diff --git a/modules/consentManagement.js b/modules/consentManagement.js index 83e5c4aab13..6c22b3b9da4 100644 --- a/modules/consentManagement.js +++ b/modules/consentManagement.js @@ -11,6 +11,7 @@ import {includes} from '../src/polyfill.js'; import {timedAuctionHook} from '../src/utils/perfMetrics.js'; import {registerOrtbProcessor, REQUEST} from '../src/pbjsORTB.js'; import {enrichFPD} from '../src/fpd/enrichment.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const DEFAULT_CMP = 'iab'; const DEFAULT_CONSENT_TIMEOUT = 10000; @@ -367,7 +368,7 @@ export function setConsentConfig(config) { } } if (!addedConsentHook) { - $$PREBID_GLOBAL$$.requestBids.before(requestBidsHook, 50); + getGlobal().requestBids.before(requestBidsHook, 50); } addedConsentHook = true; gdprDataHandler.enable(); diff --git a/modules/consentManagementGpp.js b/modules/consentManagementGpp.js index 8a9c3f999f0..3b0e1c25c6a 100644 --- a/modules/consentManagementGpp.js +++ b/modules/consentManagementGpp.js @@ -10,6 +10,7 @@ import {gppDataHandler} from '../src/adapterManager.js'; import {includes} from '../src/polyfill.js'; import {timedAuctionHook} from '../src/utils/perfMetrics.js'; import { enrichFPD } from '../src/fpd/enrichment.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const DEFAULT_CMP = 'iab'; const DEFAULT_CONSENT_TIMEOUT = 10000; @@ -362,7 +363,7 @@ export function setConsentConfig(config) { logInfo('consentManagement.gpp module has been activated...'); if (!addedConsentHook) { - $$PREBID_GLOBAL$$.requestBids.before(requestBidsHook, 50); + getGlobal().requestBids.before(requestBidsHook, 50); } addedConsentHook = true; gppDataHandler.enable(); diff --git a/modules/express.js b/modules/express.js index 0b1780e3c26..a2998baed07 100644 --- a/modules/express.js +++ b/modules/express.js @@ -1,6 +1,8 @@ import { logMessage, logWarn, logError, logInfo } from '../src/utils.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const MODULE_NAME = 'express'; +const pbjsInstance = getGlobal(); /** * Express Module @@ -12,7 +14,7 @@ const MODULE_NAME = 'express'; * * @param {Object[]} [adUnits = pbjs.adUnits] - an array of adUnits for express to operate on. */ -$$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { +pbjsInstance.express = function(adUnits = pbjsInstance.adUnits) { logMessage('loading ' + MODULE_NAME); if (adUnits.length === 0) { @@ -138,10 +140,10 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { } if (adUnits.length) { - $$PREBID_GLOBAL$$.requestBids({ + pbjsInstance.requestBids({ adUnits: adUnits, bidsBackHandler: function () { - $$PREBID_GLOBAL$$.setTargetingForGPTAsync(); + pbjsInstance.setTargetingForGPTAsync(); fGptRefresh.apply(pads(), [ adUnits.map(function (adUnit) { return gptSlotCache[adUnit.code]; @@ -168,10 +170,10 @@ $$PREBID_GLOBAL$$.express = function(adUnits = $$PREBID_GLOBAL$$.adUnits) { } if (adUnits.length) { - $$PREBID_GLOBAL$$.requestBids({ + pbjsInstance.requestBids({ adUnits: adUnits, bidsBackHandler: function () { - $$PREBID_GLOBAL$$.setTargetingForGPTAsync(); + pbjsInstance.setTargetingForGPTAsync(); fGptRefresh.apply(pads(), [ adUnits.map(function (adUnit) { return gptSlotCache[adUnit.code]; diff --git a/modules/id5AnalyticsAdapter.js b/modules/id5AnalyticsAdapter.js index d35cdf29fca..d0f3198e03d 100644 --- a/modules/id5AnalyticsAdapter.js +++ b/modules/id5AnalyticsAdapter.js @@ -4,6 +4,7 @@ import adapterManager from '../src/adapterManager.js'; import { ajax } from '../src/ajax.js'; import { logInfo, logError } from '../src/utils.js'; import * as events from '../src/events.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const { EVENTS: { @@ -34,7 +35,7 @@ const FLUSH_EVENTS = [ const CONFIG_URL_PREFIX = 'https://api.id5-sync.com/analytics' const TZ = new Date().getTimezoneOffset(); -const PBJS_VERSION = $$PREBID_GLOBAL$$.version; +const PBJS_VERSION = getGlobal().version; const ID5_REDACTED = '__ID5_REDACTED__'; const isArray = Array.isArray; diff --git a/modules/mabidderBidAdapter.js b/modules/mabidderBidAdapter.js index 12da791d2c4..632403c6643 100644 --- a/modules/mabidderBidAdapter.js +++ b/modules/mabidderBidAdapter.js @@ -1,5 +1,7 @@ import { registerBidder } from '../src/adapters/bidderFactory.js'; import { BANNER } from '../src/mediaTypes.js'; +import {getGlobal} from '../src/prebidGlobal.js'; + const BIDDER_CODE = 'mabidder'; export const baseUrl = 'https://prebid.ecdrsvc.com/bid'; export const spec = { @@ -33,7 +35,7 @@ export const spec = { url: baseUrl, method: 'POST', data: { - v: $$PREBID_GLOBAL$$.version, + v: getGlobal().version, bids: bids, url: bidderRequest.refererInfo.page || '', referer: bidderRequest.refererInfo.ref || '', diff --git a/modules/marsmediaAnalyticsAdapter.js b/modules/marsmediaAnalyticsAdapter.js index c86cc4dfbc2..f1e53a3c20c 100644 --- a/modules/marsmediaAnalyticsAdapter.js +++ b/modules/marsmediaAnalyticsAdapter.js @@ -1,6 +1,7 @@ import {ajax} from '../src/ajax.js'; import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; +import {getGlobal} from '../src/prebidGlobal.js'; /**** * Mars Media Analytics @@ -33,7 +34,7 @@ var marsmediaAnalyticsAdapter = Object.assign(adapter( success: function() {}, error: function() {} }, - JSON.stringify({act: 'prebid_analytics', params: events, 'pbjs': $$PREBID_GLOBAL$$.getBidResponses(), ver: MARS_VERSION}), + JSON.stringify({act: 'prebid_analytics', params: events, 'pbjs': getGlobal().getBidResponses(), ver: MARS_VERSION}), { method: 'POST' } diff --git a/modules/medianetAnalyticsAdapter.js b/modules/medianetAnalyticsAdapter.js index 647a02fe7dc..b902727a730 100644 --- a/modules/medianetAnalyticsAdapter.js +++ b/modules/medianetAnalyticsAdapter.js @@ -17,6 +17,7 @@ import {ajax} from '../src/ajax.js'; import {getRefererInfo} from '../src/refererDetection.js'; import {AUCTION_COMPLETED, AUCTION_IN_PROGRESS, getPriceGranularity} from '../src/auction.js'; import {includes} from '../src/polyfill.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const analyticsType = 'endpoint'; const ENDPOINT = 'https://pb-logs.media.net/log?logid=kfk&evtid=prebid_analytics_events_client'; @@ -36,7 +37,7 @@ const PRICE_GRANULARITY = { const MEDIANET_BIDDER_CODE = 'medianet'; // eslint-disable-next-line no-undef -const PREBID_VERSION = $$PREBID_GLOBAL$$.version; +const PREBID_VERSION = getGlobal().version; const ERROR_CONFIG_JSON_PARSE = 'analytics_config_parse_fail'; const ERROR_CONFIG_FETCH = 'analytics_config_ajax_fail'; const ERROR_WINNING_BID_ABSENT = 'winning_bid_absent'; @@ -886,8 +887,8 @@ medianetAnalytics.enableAnalytics = function (configuration) { logError('Media.net Analytics adapter: cid is required.'); return; } - $$PREBID_GLOBAL$$.medianetGlobals = $$PREBID_GLOBAL$$.medianetGlobals || {}; - $$PREBID_GLOBAL$$.medianetGlobals.analyticsEnabled = true; + getGlobal().medianetGlobals = getGlobal().medianetGlobals || {}; + getGlobal().medianetGlobals.analyticsEnabled = true; pageDetails = new PageDetail(); diff --git a/modules/medianetBidAdapter.js b/modules/medianetBidAdapter.js index 01652a3fac0..5f54b2e3ff3 100644 --- a/modules/medianetBidAdapter.js +++ b/modules/medianetBidAdapter.js @@ -17,6 +17,7 @@ import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js'; import {getRefererInfo} from '../src/refererDetection.js'; import {Renderer} from '../src/Renderer.js'; import { convertOrtbRequestToProprietaryNative } from '../src/native.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const BIDDER_CODE = 'medianet'; const BID_URL = 'https://prebid.media.net/rtb/prebid'; @@ -51,7 +52,7 @@ const aliases = [ { code: 'aax', gvlid: 720 }, ]; -$$PREBID_GLOBAL$$.medianetGlobals = $$PREBID_GLOBAL$$.medianetGlobals || {}; +getGlobal().medianetGlobals = getGlobal().medianetGlobals || {}; function getTopWindowReferrer() { try { @@ -177,7 +178,7 @@ function extParams(bidRequest, bidderRequests) { const coppaApplies = !!(config.getConfig('coppa')); return Object.assign({}, { customer_id: params.cid }, - { prebid_version: $$PREBID_GLOBAL$$.version }, + { prebid_version: getGlobal().version }, { gdpr_applies: gdprApplies }, (gdprApplies) && { gdpr_consent_string: gdpr.consentString || '' }, { usp_applies: uspApplies }, @@ -185,7 +186,7 @@ function extParams(bidRequest, bidderRequests) { {coppa_applies: coppaApplies}, windowSize.w !== -1 && windowSize.h !== -1 && { screen: windowSize }, userId && { user_id: userId }, - $$PREBID_GLOBAL$$.medianetGlobals.analyticsEnabled && { analytics: true }, + getGlobal().medianetGlobals.analyticsEnabled && { analytics: true }, !isEmpty(sChain) && {schain: sChain} ); } @@ -358,7 +359,7 @@ function getLoggingData(event, data) { params.evtid = 'projectevents'; params.project = 'prebid'; params.acid = deepAccess(data, '0.auctionId') || ''; - params.cid = $$PREBID_GLOBAL$$.medianetGlobals.cid || ''; + params.cid = getGlobal().medianetGlobals.cid || ''; params.crid = data.map((adunit) => deepAccess(adunit, 'params.0.crid') || adunit.adUnitCode).join('|'); params.adunit_count = data.length || 0; params.dn = mnData.urlData.domain || ''; @@ -442,7 +443,7 @@ export const spec = { return false; } - Object.assign($$PREBID_GLOBAL$$.medianetGlobals, !$$PREBID_GLOBAL$$.medianetGlobals.cid && {cid: bid.params.cid}); + Object.assign(getGlobal().medianetGlobals, !getGlobal().medianetGlobals.cid && {cid: bid.params.cid}); return true; }, diff --git a/modules/orbidderBidAdapter.js b/modules/orbidderBidAdapter.js index 9979b1fdc3b..b84c67ba6d2 100644 --- a/modules/orbidderBidAdapter.js +++ b/modules/orbidderBidAdapter.js @@ -3,6 +3,7 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import { getStorageManager } from '../src/storageManager.js'; import { BANNER, NATIVE } from '../src/mediaTypes.js'; import { convertOrtbRequestToProprietaryNative } from '../src/native.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const storageManager = getStorageManager({bidderCode: 'orbidder'}); @@ -96,7 +97,7 @@ export const spec = { method: 'POST', options: { withCredentials: true }, data: { - v: $$PREBID_GLOBAL$$.version, + v: getGlobal().version, pageUrl: referer, bidId: bidRequest.bidId, auctionId: bidRequest.auctionId, diff --git a/modules/pixfutureBidAdapter.js b/modules/pixfutureBidAdapter.js index 41b1151e72a..5019b31b90b 100644 --- a/modules/pixfutureBidAdapter.js +++ b/modules/pixfutureBidAdapter.js @@ -14,6 +14,7 @@ import { transformBidderParamKeywords } from '../src/utils.js'; import { auctionManager } from '../src/auctionManager.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const SOURCE = 'pbjs'; const storageManager = getStorageManager({bidderCode: 'pixfuture'}); @@ -132,7 +133,7 @@ export const spec = { method: 'POST', options: {withCredentials: true}, data: { - v: $$PREBID_GLOBAL$$.version, + v: getGlobal().version, pageUrl: referer, bidId: bidRequest.bidId, auctionId: bidRequest.auctionId, diff --git a/modules/pubCommonId.js b/modules/pubCommonId.js index 1fde8f8db5b..a32e26ef6c2 100644 --- a/modules/pubCommonId.js +++ b/modules/pubCommonId.js @@ -10,6 +10,7 @@ import CONSTANTS from '../src/constants.json'; import { getStorageManager } from '../src/storageManager.js'; import {timedAuctionHook} from '../src/utils/perfMetrics.js'; import {VENDORLESS_GVLID} from '../src/consentHandler.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const storage = getStorageManager({moduleName: 'pubCommonId', gvlid: VENDORLESS_GVLID}); @@ -168,7 +169,7 @@ export function getPubcidConfig() { return pubcidConfig; } */ export const requestBidHook = timedAuctionHook('pubCommonId', function requestBidHook(next, config) { - let adUnits = config.adUnits || $$PREBID_GLOBAL$$.adUnits; + let adUnits = config.adUnits || getGlobal().adUnits; let pubcid = null; // Pass control to the next function if not enabled @@ -292,7 +293,7 @@ export function initPubcid() { (storage.hasLocalStorage() && readValue(OPTOUT_NAME, LOCAL_STORAGE)); if (!optout) { - $$PREBID_GLOBAL$$.requestBids.before(requestBidHook); + getGlobal().requestBids.before(requestBidHook); } } diff --git a/modules/pubxaiAnalyticsAdapter.js b/modules/pubxaiAnalyticsAdapter.js index 96665c786bf..19a3c236942 100644 --- a/modules/pubxaiAnalyticsAdapter.js +++ b/modules/pubxaiAnalyticsAdapter.js @@ -3,6 +3,7 @@ import { ajax } from '../src/ajax.js'; import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; +import {getGlobal} from '../src/prebidGlobal.js'; const emptyUrl = ''; const analyticsType = 'endpoint'; @@ -180,7 +181,7 @@ function send(data, status) { search: { auctionTimestamp: auctionTimestamp, pubxaiAnalyticsVersion: pubxaiAnalyticsVersion, - prebidVersion: $$PREBID_GLOBAL$$.version + prebidVersion: getGlobal().version } }); if (status == 'bidwon') { diff --git a/modules/rivrAnalyticsAdapter.js b/modules/rivrAnalyticsAdapter.js index cf14ff44571..c74ce519ab9 100644 --- a/modules/rivrAnalyticsAdapter.js +++ b/modules/rivrAnalyticsAdapter.js @@ -2,6 +2,7 @@ import {ajax} from '../src/ajax.js'; import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import * as utils from '../src/utils.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const analyticsType = 'endpoint'; @@ -20,7 +21,7 @@ rivrAnalytics.originEnableAnalytics = rivrAnalytics.enableAnalytics; // override enableAnalytics so we can get access to the config passed in from the page rivrAnalytics.enableAnalytics = (config) => { if (window.rivraddon && window.rivraddon.analytics) { - window.rivraddon.analytics.enableAnalytics(config, {utils, ajax, pbjsGlobalVariable: $$PREBID_GLOBAL$$}); + window.rivraddon.analytics.enableAnalytics(config, {utils, ajax, pbjsGlobalVariable: getGlobal()}); rivrAnalytics.originEnableAnalytics(config); } }; diff --git a/modules/snigelBidAdapter.js b/modules/snigelBidAdapter.js index e0ec10c6ed6..f41fb98d436 100644 --- a/modules/snigelBidAdapter.js +++ b/modules/snigelBidAdapter.js @@ -3,6 +3,7 @@ import {registerBidder} from '../src/adapters/bidderFactory.js'; import {BANNER} from '../src/mediaTypes.js'; import {deepAccess, isArray, isFn, isPlainObject} from '../src/utils.js'; import {hasPurpose1Consent} from '../src/utils/gpdr.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const BIDDER_CODE = 'snigel'; const GVLID = 1076; @@ -33,7 +34,7 @@ export const spec = { test: getTestFlag(), devw: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, devh: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight, - version: $$PREBID_GLOBAL$$.version, + version: getGlobal().version, gdprApplies: gdprApplies, gdprConsentString: gdprApplies === true ? deepAccess(bidderRequest, 'gdprConsent.consentString') : undefined, gdprConsentProv: gdprApplies === true ? deepAccess(bidderRequest, 'gdprConsent.addtlConsent') : undefined, diff --git a/modules/tappxBidAdapter.js b/modules/tappxBidAdapter.js index 1a189f5271d..a9d08415090 100644 --- a/modules/tappxBidAdapter.js +++ b/modules/tappxBidAdapter.js @@ -6,6 +6,7 @@ import { BANNER, VIDEO } from '../src/mediaTypes.js'; import { config } from '../src/config.js'; import { Renderer } from '../src/Renderer.js'; import {parseDomain} from '../src/refererDetection.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const BIDDER_CODE = 'tappx'; const GVLID_CODE = 628; @@ -473,7 +474,7 @@ function buildOneRequest(validBidRequests, bidderRequest) { payload.regs = regs; // < Payload - let pbjsv = ($$PREBID_GLOBAL$$.version !== null) ? encodeURIComponent($$PREBID_GLOBAL$$.version) : -1; + let pbjsv = (getGlobal().version !== null) ? encodeURIComponent(getGlobal().version) : -1; return { method: 'POST', diff --git a/modules/terceptAnalyticsAdapter.js b/modules/terceptAnalyticsAdapter.js index 9d215f0ceda..c17948d73d0 100644 --- a/modules/terceptAnalyticsAdapter.js +++ b/modules/terceptAnalyticsAdapter.js @@ -3,6 +3,7 @@ import { ajax } from '../src/ajax.js'; import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js'; import adapterManager from '../src/adapterManager.js'; import CONSTANTS from '../src/constants.json'; +import {getGlobal} from '../src/prebidGlobal.js'; const emptyUrl = ''; const analyticsType = 'endpoint'; @@ -123,7 +124,7 @@ function send(data, status) { search: { auctionTimestamp: auctionTimestamp, terceptAnalyticsVersion: terceptAnalyticsVersion, - prebidVersion: $$PREBID_GLOBAL$$.version + prebidVersion: getGlobal().version } }); diff --git a/modules/yuktamediaAnalyticsAdapter.js b/modules/yuktamediaAnalyticsAdapter.js index 31c6daae7f6..a16e4ec8d36 100644 --- a/modules/yuktamediaAnalyticsAdapter.js +++ b/modules/yuktamediaAnalyticsAdapter.js @@ -6,6 +6,7 @@ import CONSTANTS from '../src/constants.json'; import {getStorageManager} from '../src/storageManager.js'; import {getRefererInfo} from '../src/refererDetection.js'; import {includes as strIncludes} from '../src/polyfill.js'; +import {getGlobal} from '../src/prebidGlobal.js'; const storage = getStorageManager(); const yuktamediaAnalyticsVersion = 'v3.1.0'; @@ -34,7 +35,7 @@ const _pageInfo = { referer: referer, refererDomain: parseUrl(referer).host, yuktamediaAnalyticsVersion: yuktamediaAnalyticsVersion, - prebidVersion: $$PREBID_GLOBAL$$.version + prebidVersion: getGlobal().version }; function getParameterByName(param) { diff --git a/package.json b/package.json index 176f496f5cc..ad625cb3045 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "prebid" ], "globalVarName": "pbjs", + "defineGlobal": true, "author": "the prebid.js contributors", "license": "Apache-2.0", "engines": { diff --git a/plugins/pbjsGlobals.js b/plugins/pbjsGlobals.js index c1a08133e8e..4c8685db840 100644 --- a/plugins/pbjsGlobals.js +++ b/plugins/pbjsGlobals.js @@ -1,4 +1,3 @@ - let t = require('@babel/core').types; let prebid = require('../package.json'); const path = require('path'); @@ -28,10 +27,12 @@ function getNpmVersion(version) { module.exports = function(api, options) { const pbGlobal = options.globalVarName || prebid.globalVarName; + const defineGlobal = typeof (options.defineGlobal) !== 'undefined' ? options.defineGlobal : prebid.defineGlobal; const features = featureMap(options.disableFeatures); let replace = { '$prebid.version$': prebid.version, '$$PREBID_GLOBAL$$': pbGlobal, + '$$DEFINE_PREBID_GLOBAL$$': defineGlobal, '$$REPO_AND_VERSION$$': `${prebid.repository.url.split('/')[3]}_prebid_${prebid.version}`, '$$PREBID_DIST_URL_BASE$$': options.prebidDistUrlBase || `https://cdn.jsdelivr.net/npm/prebid.js@${getNpmVersion(prebid.version)}/dist/` }; @@ -42,6 +43,10 @@ module.exports = function(api, options) { const PREBID_ROOT = path.resolve(__dirname, '..'); + function relPath(from, toRelToProjectRoot) { + return path.relative(path.dirname(from), path.join(PREBID_ROOT, toRelToProjectRoot)); + } + function getModuleName(filename) { const modPath = path.parse(path.relative(PREBID_ROOT, filename)); if (modPath.ext.toLowerCase() !== '.js') { @@ -63,8 +68,14 @@ module.exports = function(api, options) { Program(path, state) { const modName = getModuleName(state.filename); if (modName != null) { - // append "registration" of module file to $$PREBID_GLOBAL$$.installedModules - path.node.body.push(...api.parse(`window.${pbGlobal}.installedModules.push('${modName}');`, {filename: state.filename}).program.body); + // append "registration" of module file to getGlobal().installedModules + let i = 0; + let registerName; + do { + registerName = `__r${i++}` + } while (path.scope.hasBinding(registerName)) + path.node.body.unshift(...api.parse(`import {registerModule as ${registerName}} from '${relPath(state.filename, 'src/prebidGlobal.js')}';`, {filename: state.filename}).program.body); + path.node.body.push(...api.parse(`${registerName}('${modName}');`, {filename: state.filename}).program.body); } }, StringLiteral(path) { @@ -72,7 +83,7 @@ module.exports = function(api, options) { if (path.node.value.includes(name)) { path.node.value = path.node.value.replace( new RegExp(escapeRegExp(name), 'g'), - replace[name] + replace[name].toString() ); } }); @@ -102,7 +113,7 @@ module.exports = function(api, options) { ); } else { path.replaceWith( - t.Identifier(replace[name]) + t.Identifier(replace[name].toString()) ); } } diff --git a/src/Renderer.js b/src/Renderer.js index 97e37084e89..cdee9c79e63 100644 --- a/src/Renderer.js +++ b/src/Renderer.js @@ -3,6 +3,9 @@ import { logError, logWarn, logMessage, deepAccess } from './utils.js'; import {find} from './polyfill.js'; +import {getGlobal} from './prebidGlobal.js'; + +const pbjsInstance = getGlobal(); const moduleCode = 'outstream'; /** @@ -129,7 +132,7 @@ export function executeRenderer(renderer, bid, doc) { } function isRendererPreferredFromAdUnit(adUnitCode) { - const adUnits = $$PREBID_GLOBAL$$.adUnits; + const adUnits = pbjsInstance.adUnits; const adUnit = find(adUnits, adUnit => { return adUnit.code === adUnitCode; }); diff --git a/src/auction.js b/src/auction.js index a1e0fe13573..2cb93b82ef7 100644 --- a/src/auction.js +++ b/src/auction.js @@ -94,6 +94,7 @@ import {GreedyPromise} from './utils/promise.js'; import {useMetrics} from './utils/perfMetrics.js'; import {createBid} from './bidfactory.js'; import {adjustCpm} from './utils/cpm.js'; +import {getGlobal} from './prebidGlobal.js'; const { syncUsers } = userSync; @@ -111,6 +112,8 @@ const outstandingRequests = {}; const sourceInfo = {}; const queuedCalls = []; +const pbjsInstance = getGlobal(); + /** * Clear global state for tests */ @@ -216,7 +219,7 @@ export function newAuction({adUnits, adUnitCodes, callback, cbTimeout, labels, a const bids = _bidsReceived .filter(bind.call(adUnitsFilter, this, adUnitCodes)) .reduce(groupByPlacement, {}); - _callback.apply($$PREBID_GLOBAL$$, [bids, timedOut, _auctionId]); + _callback.apply(pbjsInstance, [bids, timedOut, _auctionId]); _callback = null; } } catch (e) { diff --git a/src/prebid.js b/src/prebid.js index 70653de0bcb..7ddebed6fd9 100644 --- a/src/prebid.js +++ b/src/prebid.js @@ -52,7 +52,7 @@ import {newMetrics, useMetrics} from './utils/perfMetrics.js'; import {defer, GreedyPromise} from './utils/promise.js'; import {enrichFPD} from './fpd/enrichment.js'; -const $$PREBID_GLOBAL$$ = getGlobal(); +const pbjsInstance = getGlobal(); const { triggerUserSyncs } = userSync; /* private variables */ @@ -67,22 +67,22 @@ const eventValidators = { loadSession(); /* Public vars */ -$$PREBID_GLOBAL$$.bidderSettings = $$PREBID_GLOBAL$$.bidderSettings || {}; +pbjsInstance.bidderSettings = pbjsInstance.bidderSettings || {}; // let the world know we are loaded -$$PREBID_GLOBAL$$.libLoaded = true; +pbjsInstance.libLoaded = true; // version auto generated from build -$$PREBID_GLOBAL$$.version = 'v$prebid.version$'; +pbjsInstance.version = 'v$prebid.version$'; logInfo('Prebid.js v$prebid.version$ loaded'); -$$PREBID_GLOBAL$$.installedModules = $$PREBID_GLOBAL$$.installedModules || []; +pbjsInstance.installedModules = pbjsInstance.installedModules || []; // create adUnit array -$$PREBID_GLOBAL$$.adUnits = $$PREBID_GLOBAL$$.adUnits || []; +pbjsInstance.adUnits = pbjsInstance.adUnits || []; // Allow publishers who enable user sync override to trigger their sync -$$PREBID_GLOBAL$$.triggerUserSyncs = triggerUserSyncs; +pbjsInstance.triggerUserSyncs = triggerUserSyncs; function checkDefinedPlacement(id) { var adUnitCodes = auctionManager.getBidsRequested().map(bidSet => bidSet.bids.map(bid => bid.adUnitCode)) @@ -277,12 +277,12 @@ export const checkAdUnitSetup = hook('sync', function (adUnits) { * @alias module:pbjs.getAdserverTargetingForAdUnitCodeStr * @return {Array} returnObj return bids array */ -$$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr = function (adunitCode) { +pbjsInstance.getAdserverTargetingForAdUnitCodeStr = function (adunitCode) { logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr', arguments); // call to retrieve bids array if (adunitCode) { - var res = $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode(adunitCode); + var res = pbjsInstance.getAdserverTargetingForAdUnitCode(adunitCode); return transformAdServerTargetingObj(res); } else { logMessage('Need to call getAdserverTargetingForAdUnitCodeStr with adunitCode'); @@ -295,7 +295,7 @@ $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr = function (adunitCode) { * @alias module:pbjs.getHighestUnusedBidResponseForAdUnitCode * @returns {Object} returnObj return bid */ -$$PREBID_GLOBAL$$.getHighestUnusedBidResponseForAdUnitCode = function (adunitCode) { +pbjsInstance.getHighestUnusedBidResponseForAdUnitCode = function (adunitCode) { if (adunitCode) { const bid = auctionManager.getAllBidsForAdUnitCode(adunitCode) .filter(isBidUsable) @@ -312,8 +312,8 @@ $$PREBID_GLOBAL$$.getHighestUnusedBidResponseForAdUnitCode = function (adunitCod * @alias module:pbjs.getAdserverTargetingForAdUnitCode * @returns {Object} returnObj return bids */ -$$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode = function (adUnitCode) { - return $$PREBID_GLOBAL$$.getAdserverTargeting(adUnitCode)[adUnitCode]; +pbjsInstance.getAdserverTargetingForAdUnitCode = function (adUnitCode) { + return pbjsInstance.getAdserverTargeting(adUnitCode)[adUnitCode]; }; /** @@ -322,7 +322,7 @@ $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode = function (adUnitCode) { * @alias module:pbjs.getAdserverTargeting */ -$$PREBID_GLOBAL$$.getAdserverTargeting = function (adUnitCode) { +pbjsInstance.getAdserverTargeting = function (adUnitCode) { logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargeting', arguments); return targeting.getAllTargeting(adUnitCode); }; @@ -341,7 +341,7 @@ function getConsentMetadata() { } } -$$PREBID_GLOBAL$$.getConsentMetadata = function () { +pbjsInstance.getConsentMetadata = function () { logInfo('Invoking $$PREBID_GLOBAL$$.getConsentMetadata'); return getConsentMetadata(); }; @@ -372,7 +372,7 @@ function getBids(type) { * @return {Object} map | object that contains the bidRequests */ -$$PREBID_GLOBAL$$.getNoBids = function () { +pbjsInstance.getNoBids = function () { logInfo('Invoking $$PREBID_GLOBAL$$.getNoBids', arguments); return getBids('getNoBids'); }; @@ -384,7 +384,7 @@ $$PREBID_GLOBAL$$.getNoBids = function () { * @return {Object} bidResponse object */ -$$PREBID_GLOBAL$$.getNoBidsForAdUnitCode = function (adUnitCode) { +pbjsInstance.getNoBidsForAdUnitCode = function (adUnitCode) { const bids = auctionManager.getNoBids().filter(bid => bid.adUnitCode === adUnitCode); return { bids }; }; @@ -395,7 +395,7 @@ $$PREBID_GLOBAL$$.getNoBidsForAdUnitCode = function (adUnitCode) { * @return {Object} map | object that contains the bidResponses */ -$$PREBID_GLOBAL$$.getBidResponses = function () { +pbjsInstance.getBidResponses = function () { logInfo('Invoking $$PREBID_GLOBAL$$.getBidResponses', arguments); return getBids('getBidsReceived'); }; @@ -407,7 +407,7 @@ $$PREBID_GLOBAL$$.getBidResponses = function () { * @return {Object} bidResponse object */ -$$PREBID_GLOBAL$$.getBidResponsesForAdUnitCode = function (adUnitCode) { +pbjsInstance.getBidResponsesForAdUnitCode = function (adUnitCode) { const bids = auctionManager.getBidsReceived().filter(bid => bid.adUnitCode === adUnitCode); return { bids }; }; @@ -418,7 +418,7 @@ $$PREBID_GLOBAL$$.getBidResponsesForAdUnitCode = function (adUnitCode) { * @param {function(object)} customSlotMatching gets a GoogleTag slot and returns a filter function for adUnitCode, so you can decide to match on either eg. return slot => { return adUnitCode => { return slot.getSlotElementId() === 'myFavoriteDivId'; } }; * @alias module:pbjs.setTargetingForGPTAsync */ -$$PREBID_GLOBAL$$.setTargetingForGPTAsync = function (adUnit, customSlotMatching) { +pbjsInstance.setTargetingForGPTAsync = function (adUnit, customSlotMatching) { logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForGPTAsync', arguments); if (!isGptPubadsDefined()) { logError('window.googletag is not defined on the page'); @@ -451,7 +451,7 @@ $$PREBID_GLOBAL$$.setTargetingForGPTAsync = function (adUnit, customSlotMatching * @param {(string|string[])} adUnitCode adUnitCode or array of adUnitCodes * @alias module:pbjs.setTargetingForAst */ -$$PREBID_GLOBAL$$.setTargetingForAst = function (adUnitCodes) { +pbjsInstance.setTargetingForAst = function (adUnitCodes) { logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForAn', arguments); if (!targeting.isApntagDefined()) { logError('window.apntag is not defined on the page'); @@ -484,7 +484,7 @@ function reinjectNodeIfRemoved(node, doc, tagName) { * @param {string} id bid id to locate the ad * @alias module:pbjs.renderAd */ -$$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { +pbjsInstance.renderAd = hook('async', function (doc, id, options) { logInfo('Invoking $$PREBID_GLOBAL$$.renderAd', arguments); logMessage('Calling renderAd with adId :' + id); @@ -531,8 +531,8 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { // video module const adUnitCode = bid.adUnitCode; - const adUnit = $$PREBID_GLOBAL$$.adUnits.filter(adUnit => adUnit.code === adUnitCode); - const videoModule = $$PREBID_GLOBAL$$.videoModule; + const adUnit = pbjsInstance.adUnits.filter(adUnit => adUnit.code === adUnitCode); + const videoModule = pbjsInstance.videoModule; if (adUnit.video && videoModule) { videoModule.renderBid(adUnit.video.divId, bid); return; @@ -589,11 +589,11 @@ $$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) { * @param {string| Array} adUnitCode the adUnitCode(s) to remove * @alias module:pbjs.removeAdUnit */ -$$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { +pbjsInstance.removeAdUnit = function (adUnitCode) { logInfo('Invoking $$PREBID_GLOBAL$$.removeAdUnit', arguments); if (!adUnitCode) { - $$PREBID_GLOBAL$$.adUnits = []; + pbjsInstance.adUnits = []; return; } @@ -606,9 +606,9 @@ $$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { } adUnitCodes.forEach((adUnitCode) => { - for (let i = $$PREBID_GLOBAL$$.adUnits.length - 1; i >= 0; i--) { - if ($$PREBID_GLOBAL$$.adUnits[i].code === adUnitCode) { - $$PREBID_GLOBAL$$.adUnits.splice(i, 1); + for (let i = pbjsInstance.adUnits.length - 1; i >= 0; i--) { + if (pbjsInstance.adUnits[i].code === adUnitCode) { + pbjsInstance.adUnits.splice(i, 1); } } }); @@ -624,7 +624,7 @@ $$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) { * @param {String} requestOptions.auctionId * @alias module:pbjs.requestBids */ -$$PREBID_GLOBAL$$.requestBids = (function() { +pbjsInstance.requestBids = (function() { const delegate = hook('async', function ({ bidsBackHandler, timeout, adUnits, adUnitCodes, labels, auctionId, ttlBuffer, ortb2, metrics, defer } = {}) { events.emit(REQUEST_BIDS); const cbTimeout = timeout || config.getConfig('bidderTimeout'); @@ -653,7 +653,7 @@ $$PREBID_GLOBAL$$.requestBids = (function() { // if the request does not specify adUnits, clone the global adUnit array; // otherwise, if the caller goes on to use addAdUnits/removeAdUnits, any asynchronous logic // in any hook might see their effects. - let adUnits = req.adUnits || $$PREBID_GLOBAL$$.adUnits; + let adUnits = req.adUnits || pbjsInstance.adUnits; req.adUnits = (isArray(adUnits) ? adUnits.slice() : [adUnits]); req.metrics = newMetrics(); @@ -761,7 +761,7 @@ export function executeCallbacks(fn, reqBidsConfigObj) { } // This hook will execute all storage callbacks which were registered before gdpr enforcement hook was added. Some bidders, user id modules use storage functions when module is parsed but gdpr enforcement hook is not added at that stage as setConfig callbacks are yet to be called. Hence for such calls we execute all the stored callbacks just before requestBids. At this hook point we will know for sure that gdprEnforcement module is added or not -$$PREBID_GLOBAL$$.requestBids.before(executeCallbacks, 49); +pbjsInstance.requestBids.before(executeCallbacks, 49); /** * @@ -769,9 +769,9 @@ $$PREBID_GLOBAL$$.requestBids.before(executeCallbacks, 49); * @param {Array|Object} adUnitArr Array of adUnits or single adUnit Object. * @alias module:pbjs.addAdUnits */ -$$PREBID_GLOBAL$$.addAdUnits = function (adUnitArr) { +pbjsInstance.addAdUnits = function (adUnitArr) { logInfo('Invoking $$PREBID_GLOBAL$$.addAdUnits', arguments); - $$PREBID_GLOBAL$$.adUnits.push.apply($$PREBID_GLOBAL$$.adUnits, isArray(adUnitArr) ? adUnitArr : [adUnitArr]); + pbjsInstance.adUnits.push.apply(pbjsInstance.adUnits, isArray(adUnitArr) ? adUnitArr : [adUnitArr]); // emit event events.emit(ADD_AD_UNITS); }; @@ -792,7 +792,7 @@ $$PREBID_GLOBAL$$.addAdUnits = function (adUnitArr) { * * Currently `bidWon` is the only event that accepts an `id` parameter. */ -$$PREBID_GLOBAL$$.onEvent = function (event, handler, id) { +pbjsInstance.onEvent = function (event, handler, id) { logInfo('Invoking $$PREBID_GLOBAL$$.onEvent', arguments); if (!isFn(handler)) { logError('The event handler provided is not a function and was not set on event "' + event + '".'); @@ -813,7 +813,7 @@ $$PREBID_GLOBAL$$.onEvent = function (event, handler, id) { * @param {string} id an identifier in the context of the event (see `$$PREBID_GLOBAL$$.onEvent`) * @alias module:pbjs.offEvent */ -$$PREBID_GLOBAL$$.offEvent = function (event, handler, id) { +pbjsInstance.offEvent = function (event, handler, id) { logInfo('Invoking $$PREBID_GLOBAL$$.offEvent', arguments); if (id && !eventValidators[event].call(null, id)) { return; @@ -827,7 +827,7 @@ $$PREBID_GLOBAL$$.offEvent = function (event, handler, id) { * * @alias module:pbjs.getEvents */ -$$PREBID_GLOBAL$$.getEvents = function () { +pbjsInstance.getEvents = function () { logInfo('Invoking $$PREBID_GLOBAL$$.getEvents'); return events.getEvents(); }; @@ -838,7 +838,7 @@ $$PREBID_GLOBAL$$.getEvents = function () { * @param {string} bidderCode [description] * @alias module:pbjs.registerBidAdapter */ -$$PREBID_GLOBAL$$.registerBidAdapter = function (bidderAdaptor, bidderCode) { +pbjsInstance.registerBidAdapter = function (bidderAdaptor, bidderCode) { logInfo('Invoking $$PREBID_GLOBAL$$.registerBidAdapter', arguments); try { adapterManager.registerBidAdapter(bidderAdaptor(), bidderCode); @@ -852,7 +852,7 @@ $$PREBID_GLOBAL$$.registerBidAdapter = function (bidderAdaptor, bidderCode) { * @param {Object} options [description] * @alias module:pbjs.registerAnalyticsAdapter */ -$$PREBID_GLOBAL$$.registerAnalyticsAdapter = function (options) { +pbjsInstance.registerAnalyticsAdapter = function (options) { logInfo('Invoking $$PREBID_GLOBAL$$.registerAnalyticsAdapter', arguments); try { adapterManager.registerAnalyticsAdapter(options); @@ -867,7 +867,7 @@ $$PREBID_GLOBAL$$.registerAnalyticsAdapter = function (options) { * @alias module:pbjs.createBid * @return {Object} bidResponse [description] */ -$$PREBID_GLOBAL$$.createBid = function (statusCode) { +pbjsInstance.createBid = function (statusCode) { logInfo('Invoking $$PREBID_GLOBAL$$.createBid', arguments); return createBid(statusCode); }; @@ -899,14 +899,14 @@ const enableAnalyticsCb = hook('async', function (config) { } }, 'enableAnalyticsCb'); -$$PREBID_GLOBAL$$.enableAnalytics = function (config) { +pbjsInstance.enableAnalytics = function (config) { enableAnalyticsCallbacks.push(enableAnalyticsCb.bind(this, config)); }; /** * @alias module:pbjs.aliasBidder */ -$$PREBID_GLOBAL$$.aliasBidder = function (bidderCode, alias, options) { +pbjsInstance.aliasBidder = function (bidderCode, alias, options) { logInfo('Invoking $$PREBID_GLOBAL$$.aliasBidder', arguments); if (bidderCode && alias) { adapterManager.aliasBidAdapter(bidderCode, alias, options); @@ -918,9 +918,9 @@ $$PREBID_GLOBAL$$.aliasBidder = function (bidderCode, alias, options) { /** * @alias module:pbjs.aliasRegistry */ -$$PREBID_GLOBAL$$.aliasRegistry = adapterManager.aliasRegistry; +pbjsInstance.aliasRegistry = adapterManager.aliasRegistry; config.getConfig('aliasRegistry', config => { - if (config.aliasRegistry === 'private') delete $$PREBID_GLOBAL$$.aliasRegistry; + if (config.aliasRegistry === 'private') delete pbjsInstance.aliasRegistry; }); /** @@ -962,7 +962,7 @@ config.getConfig('aliasRegistry', config => { * Get all of the bids that have been rendered. Useful for [troubleshooting your integration](http://prebid.org/dev-docs/prebid-troubleshooting-guide.html). * @return {Array} A list of bids that have been rendered. */ -$$PREBID_GLOBAL$$.getAllWinningBids = function () { +pbjsInstance.getAllWinningBids = function () { return auctionManager.getAllWinningBids(); }; @@ -970,7 +970,7 @@ $$PREBID_GLOBAL$$.getAllWinningBids = function () { * Get all of the bids that have won their respective auctions. * @return {Array} A list of bids that have won their respective auctions. */ -$$PREBID_GLOBAL$$.getAllPrebidWinningBids = function () { +pbjsInstance.getAllPrebidWinningBids = function () { return auctionManager.getBidsReceived() .filter(bid => bid.status === CONSTANTS.BID_STATUS.BID_TARGETING_SET); }; @@ -982,7 +982,7 @@ $$PREBID_GLOBAL$$.getAllPrebidWinningBids = function () { * @alias module:pbjs.getHighestCpmBids * @return {Array} array containing highest cpm bid object(s) */ -$$PREBID_GLOBAL$$.getHighestCpmBids = function (adUnitCode) { +pbjsInstance.getHighestCpmBids = function (adUnitCode) { return targeting.getWinningBids(adUnitCode); }; @@ -994,7 +994,7 @@ $$PREBID_GLOBAL$$.getHighestCpmBids = function (adUnitCode) { * * @alias module:pbjs.markWinningBidAsUsed */ -$$PREBID_GLOBAL$$.markWinningBidAsUsed = function (markBidRequest) { +pbjsInstance.markWinningBidAsUsed = function (markBidRequest) { let bids = []; if (markBidRequest.adUnitCode && markBidRequest.adId) { @@ -1020,10 +1020,10 @@ $$PREBID_GLOBAL$$.markWinningBidAsUsed = function (markBidRequest) { * @param {Object} options * @alias module:pbjs.getConfig */ -$$PREBID_GLOBAL$$.getConfig = config.getAnyConfig; -$$PREBID_GLOBAL$$.readConfig = config.readAnyConfig; -$$PREBID_GLOBAL$$.mergeConfig = config.mergeConfig; -$$PREBID_GLOBAL$$.mergeBidderConfig = config.mergeBidderConfig; +pbjsInstance.getConfig = config.getAnyConfig; +pbjsInstance.readConfig = config.readAnyConfig; +pbjsInstance.mergeConfig = config.mergeConfig; +pbjsInstance.mergeBidderConfig = config.mergeBidderConfig; /** * Set Prebid config options. @@ -1031,10 +1031,10 @@ $$PREBID_GLOBAL$$.mergeBidderConfig = config.mergeBidderConfig; * * @param {Object} options Global Prebid configuration object. Must be JSON - no JavaScript functions are allowed. */ -$$PREBID_GLOBAL$$.setConfig = config.setConfig; -$$PREBID_GLOBAL$$.setBidderConfig = config.setBidderConfig; +pbjsInstance.setConfig = config.setConfig; +pbjsInstance.setBidderConfig = config.setBidderConfig; -$$PREBID_GLOBAL$$.que.push(() => listenMessagesFromCreative()); +pbjsInstance.que.push(() => listenMessagesFromCreative()); /** * This queue lets users load Prebid asynchronously, but run functions the same way regardless of whether it gets loaded @@ -1056,7 +1056,7 @@ $$PREBID_GLOBAL$$.que.push(() => listenMessagesFromCreative()); * the Prebid script has been fully loaded. * @alias module:pbjs.cmd.push */ -$$PREBID_GLOBAL$$.cmd.push = function (command) { +pbjsInstance.cmd.push = function (command) { if (typeof command === 'function') { try { command.call(); @@ -1068,7 +1068,7 @@ $$PREBID_GLOBAL$$.cmd.push = function (command) { } }; -$$PREBID_GLOBAL$$.que.push = $$PREBID_GLOBAL$$.cmd.push; +pbjsInstance.que.push = pbjsInstance.cmd.push; function processQueue(queue) { queue.forEach(function (cmd) { @@ -1086,10 +1086,10 @@ function processQueue(queue) { /** * @alias module:pbjs.processQueue */ -$$PREBID_GLOBAL$$.processQueue = function () { +pbjsInstance.processQueue = function () { hook.ready(); - processQueue($$PREBID_GLOBAL$$.que); - processQueue($$PREBID_GLOBAL$$.cmd); + processQueue(pbjsInstance.que); + processQueue(pbjsInstance.cmd); }; -export default $$PREBID_GLOBAL$$; +export default pbjsInstance; diff --git a/src/prebidGlobal.js b/src/prebidGlobal.js index 5eed4b3670f..4cbc3e10ad1 100644 --- a/src/prebidGlobal.js +++ b/src/prebidGlobal.js @@ -1,13 +1,21 @@ // if $$PREBID_GLOBAL$$ already exists in global document scope, use it, if not, create the object // global defination should happen BEFORE imports to avoid global undefined errors. -window.$$PREBID_GLOBAL$$ = (window.$$PREBID_GLOBAL$$ || {}); -window.$$PREBID_GLOBAL$$.cmd = window.$$PREBID_GLOBAL$$.cmd || []; -window.$$PREBID_GLOBAL$$.que = window.$$PREBID_GLOBAL$$.que || []; +/* global $$DEFINE_PREBID_GLOBAL$$ */ +const scope = !$$DEFINE_PREBID_GLOBAL$$ ? {} : window; +const global = scope.$$PREBID_GLOBAL$$ = scope.$$PREBID_GLOBAL$$ || {}; +global.cmd = global.cmd || []; +global.que = global.que || []; // create a pbjs global pointer -window._pbjsGlobals = window._pbjsGlobals || []; -window._pbjsGlobals.push('$$PREBID_GLOBAL$$'); +if (scope === window) { + scope._pbjsGlobals = scope._pbjsGlobals || []; + scope._pbjsGlobals.push('$$PREBID_GLOBAL$$'); +} export function getGlobal() { - return window.$$PREBID_GLOBAL$$; + return global; +} + +export function registerModule(name) { + global.installedModules.push(name); } diff --git a/src/utils.js b/src/utils.js index 8df45bab9d2..17b910ff722 100644 --- a/src/utils.js +++ b/src/utils.js @@ -3,6 +3,7 @@ import clone from 'just-clone'; import {find, includes} from './polyfill.js'; import CONSTANTS from './constants.json'; import {GreedyPromise} from './utils/promise.js'; +import {getGlobal} from './prebidGlobal.js'; export { default as deepAccess } from 'dlv/index.js'; export { dset as deepSetValue } from 'dset'; @@ -21,6 +22,8 @@ let consoleErrorExists = Boolean(consoleExists && window.console.error); let eventEmitter; +const pbjsInstance = getGlobal(); + export function _setEventEmitter(emitFn) { // called from events.js - this hoop is to avoid circular imports eventEmitter = emitFn; @@ -707,7 +710,7 @@ export function getKeyByValue(obj, value) { } } -export function getBidderCodes(adUnits = $$PREBID_GLOBAL$$.adUnits) { +export function getBidderCodes(adUnits = pbjsInstance.adUnits) { // this could memoize adUnits return adUnits.map(unit => unit.bids.map(bid => bid.bidder) .reduce(flatten, [])).reduce(flatten, []).filter((bidder) => typeof bidder !== 'undefined').filter(uniques);