language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function* publisherPublishSession() { /** select session data from store */ const sessionTopic = yield select(selectSocketSessionTopic()); const username = yield select(selectSocketUsername()); try { /** api call to store session in db */ const { sessionId, sessionTimestamp, sessionToken, sessionUsername, } = yield call(publishSession, { sessionTopic, username, }); /** update store with db data */ yield put( socketPublisherPublishSessionSuccess({ sessionId, sessionTimestamp, sessionToken, sessionTopic, sessionUsername, }), ); } catch (error) { /** handle error */ yield put(socketPublisherPublishSessionFailure({ error })); } }
function* publisherPublishSession() { /** select session data from store */ const sessionTopic = yield select(selectSocketSessionTopic()); const username = yield select(selectSocketUsername()); try { /** api call to store session in db */ const { sessionId, sessionTimestamp, sessionToken, sessionUsername, } = yield call(publishSession, { sessionTopic, username, }); /** update store with db data */ yield put( socketPublisherPublishSessionSuccess({ sessionId, sessionTimestamp, sessionToken, sessionTopic, sessionUsername, }), ); } catch (error) { /** handle error */ yield put(socketPublisherPublishSessionFailure({ error })); } }
JavaScript
function* publisherPublishUser() { const sessionId = yield select(selectSocketSessionId()); const username = yield select(selectSocketUsername()); try { const { userId, userToken } = yield call(publishUser, { sessionId, username, }); yield put( socketPublisherPublishUserSuccess({ userId, userToken, }), ); } catch (error) { yield put(socketPublisherPublishUserFailure({ error })); } }
function* publisherPublishUser() { const sessionId = yield select(selectSocketSessionId()); const username = yield select(selectSocketUsername()); try { const { userId, userToken } = yield call(publishUser, { sessionId, username, }); yield put( socketPublisherPublishUserSuccess({ userId, userToken, }), ); } catch (error) { yield put(socketPublisherPublishUserFailure({ error })); } }
JavaScript
function* publisherSubscribeActions() { const sessionId = yield select(selectSocketSessionId()); try { const channel = yield call(subscribeActions, { sessionId }); yield put(socketPublisherSubscribeActionsSuccess()); while (true) { const { payload, type } = yield take(channel); yield put(socketPublisherReceiveAction({ payload, type })); } } catch (error) { yield put(socketPublisherSubscribeActionsFailure({ error })); } }
function* publisherSubscribeActions() { const sessionId = yield select(selectSocketSessionId()); try { const channel = yield call(subscribeActions, { sessionId }); yield put(socketPublisherSubscribeActionsSuccess()); while (true) { const { payload, type } = yield take(channel); yield put(socketPublisherReceiveAction({ payload, type })); } } catch (error) { yield put(socketPublisherSubscribeActionsFailure({ error })); } }
JavaScript
function* publisherUnpublishUser() { const sessionId = yield select(selectSocketSessionId()); const userId = yield select(selectSocketUserId()); const userToken = yield select(selectSocketUserToken()); try { yield call(unpublishUser, { sessionId, userToken, userId }); yield put(socketPublisherUnpublishUserSuccess()); } catch (error) { yield put(socketPublisherUnpublishUserFailure({ error })); } }
function* publisherUnpublishUser() { const sessionId = yield select(selectSocketSessionId()); const userId = yield select(selectSocketUserId()); const userToken = yield select(selectSocketUserToken()); try { yield call(unpublishUser, { sessionId, userToken, userId }); yield put(socketPublisherUnpublishUserSuccess()); } catch (error) { yield put(socketPublisherUnpublishUserFailure({ error })); } }
JavaScript
function* publisherUnsubscribeActions() { const sessionId = yield select(selectSocketSessionId()); try { yield call(unsubscribeActions, { sessionId }); yield put(socketPublisherUnsubscribeActionsSuccess()); } catch (error) { yield put(socketPublisherUnsubscribeActionsFailure({ error })); } }
function* publisherUnsubscribeActions() { const sessionId = yield select(selectSocketSessionId()); try { yield call(unsubscribeActions, { sessionId }); yield put(socketPublisherUnsubscribeActionsSuccess()); } catch (error) { yield put(socketPublisherUnsubscribeActionsFailure({ error })); } }
JavaScript
function* publisherUnsubscribeUsers() { const sessionId = yield select(selectSocketSessionId()); try { yield call(unsubscribeUsers, { sessionId }); yield put(socketPublisherUnsubscribeUsersSuccess()); } catch (error) { yield put(socketPublisherUnsubscribeUsersFailure({ error })); } }
function* publisherUnsubscribeUsers() { const sessionId = yield select(selectSocketSessionId()); try { yield call(unsubscribeUsers, { sessionId }); yield put(socketPublisherUnsubscribeUsersSuccess()); } catch (error) { yield put(socketPublisherUnsubscribeUsersFailure({ error })); } }
JavaScript
function* publisherSubscribeUsers() { const sessionId = yield select(selectSocketSessionId()); try { const channel = yield call(subscribeUsers, { sessionId }); yield put(socketPublisherSubscribeUsersSuccess()); while (true) { const { change, username } = yield take(channel); yield put( socketPublisherReceiveUser({ change, username, }), ); } } catch (error) { yield put( socketPublisherSubscribeUsersFailure({ error, }), ); } }
function* publisherSubscribeUsers() { const sessionId = yield select(selectSocketSessionId()); try { const channel = yield call(subscribeUsers, { sessionId }); yield put(socketPublisherSubscribeUsersSuccess()); while (true) { const { change, username } = yield take(channel); yield put( socketPublisherReceiveUser({ change, username, }), ); } } catch (error) { yield put( socketPublisherSubscribeUsersFailure({ error, }), ); } }
JavaScript
function clickCatalog(Event) { if(clientID == 0 && gameStarted == false) { for(var i = 0; i < countCatalog; i++) { var tmpCatalog = document.getElementById("catalog" + i); tmpCatalog.style.color = "white"; } var activeCatalog = Event.target; activeCatalog.style.color = "red"; var catalogChange = { "Type": "5", "Length" : activeCatalog.innerHTML.length, "Filename" : activeCatalog.innerHTML + ".xml" }; playerSocket.send(JSON.stringify(catalogChange)); } }
function clickCatalog(Event) { if(clientID == 0 && gameStarted == false) { for(var i = 0; i < countCatalog; i++) { var tmpCatalog = document.getElementById("catalog" + i); tmpCatalog.style.color = "white"; } var activeCatalog = Event.target; activeCatalog.style.color = "red"; var catalogChange = { "Type": "5", "Length" : activeCatalog.innerHTML.length, "Filename" : activeCatalog.innerHTML + ".xml" }; playerSocket.send(JSON.stringify(catalogChange)); } }
JavaScript
function checkEnoughPlayer () { if(clientID == 0) { // Nur Spielleiter kann das Spiel starten if(document.getElementById("divEnoughPlayer") != null){ var startGame = document.getElementById("divEnoughPlayer"); startGame.parentNode.removeChild(startGame); } if(countPlayer > 1) { var enoughPlayer = document.getElementById("startGame"); var div = document.createElement("div"); div.setAttribute("role","alert"); div.setAttribute("class","alert alert-success"); div.setAttribute("id","divEnoughPlayer"); var button = document.createElement("button"); button.setAttribute("class", "btn btn-primary"); button.setAttribute("type", "button"); var t = document.createTextNode("Spiel starten"); button.appendChild(t); div.appendChild(button); enoughPlayer.appendChild(div); button.addEventListener("click", btnEnoughPlayerListener, false); } } }
function checkEnoughPlayer () { if(clientID == 0) { // Nur Spielleiter kann das Spiel starten if(document.getElementById("divEnoughPlayer") != null){ var startGame = document.getElementById("divEnoughPlayer"); startGame.parentNode.removeChild(startGame); } if(countPlayer > 1) { var enoughPlayer = document.getElementById("startGame"); var div = document.createElement("div"); div.setAttribute("role","alert"); div.setAttribute("class","alert alert-success"); div.setAttribute("id","divEnoughPlayer"); var button = document.createElement("button"); button.setAttribute("class", "btn btn-primary"); button.setAttribute("type", "button"); var t = document.createTextNode("Spiel starten"); button.appendChild(t); div.appendChild(button); enoughPlayer.appendChild(div); button.addEventListener("click", btnEnoughPlayerListener, false); } } }
JavaScript
decode(value, configParams) { function composeIdObject(value) { const base = { 'lipbid': value['unifiedId'] }; delete value.unifiedId; return { 'lipb': { ...base, ...value } }; } if (configParams) { initializeLiveConnect(configParams); tryFireEvent(); } return (value && typeof value['unifiedId'] === 'string') ? composeIdObject(value) : undefined; }
decode(value, configParams) { function composeIdObject(value) { const base = { 'lipbid': value['unifiedId'] }; delete value.unifiedId; return { 'lipb': { ...base, ...value } }; } if (configParams) { initializeLiveConnect(configParams); tryFireEvent(); } return (value && typeof value['unifiedId'] === 'string') ? composeIdObject(value) : undefined; }
JavaScript
function buildDfpVideoUrl(options) { if (!options.params && !options.url) { logError(`A params object or a url is required to use $$PREBID_GLOBAL$$.adServers.dfp.buildVideoUrl`); return; } const adUnit = options.adUnit; const bid = options.bid || targeting.getWinningBids(adUnit.code)[0]; let urlComponents = {}; if (options.url) { // when both `url` and `params` are given, parsed url will be overwriten // with any matching param components urlComponents = parseUrl(options.url, {noDecodeWholeURL: true}); if (isEmpty(options.params)) { return buildUrlFromAdserverUrlComponents(urlComponents, bid, options); } } const derivedParams = { correlator: Date.now(), sz: parseSizesInput(adUnit.sizes).join('|'), url: encodeURIComponent(location.href), }; const encodedCustomParams = getCustParams(bid, options); const queryParams = Object.assign({}, defaultParamConstants, urlComponents.search, derivedParams, options.params, { cust_params: encodedCustomParams } ); const descriptionUrl = getDescriptionUrl(bid, options, 'params'); if (descriptionUrl) { queryParams.description_url = descriptionUrl; } return buildUrl({ protocol: 'https', host: 'securepubads.g.doubleclick.net', pathname: '/gampad/ads', search: queryParams }); }
function buildDfpVideoUrl(options) { if (!options.params && !options.url) { logError(`A params object or a url is required to use $$PREBID_GLOBAL$$.adServers.dfp.buildVideoUrl`); return; } const adUnit = options.adUnit; const bid = options.bid || targeting.getWinningBids(adUnit.code)[0]; let urlComponents = {}; if (options.url) { // when both `url` and `params` are given, parsed url will be overwriten // with any matching param components urlComponents = parseUrl(options.url, {noDecodeWholeURL: true}); if (isEmpty(options.params)) { return buildUrlFromAdserverUrlComponents(urlComponents, bid, options); } } const derivedParams = { correlator: Date.now(), sz: parseSizesInput(adUnit.sizes).join('|'), url: encodeURIComponent(location.href), }; const encodedCustomParams = getCustParams(bid, options); const queryParams = Object.assign({}, defaultParamConstants, urlComponents.search, derivedParams, options.params, { cust_params: encodedCustomParams } ); const descriptionUrl = getDescriptionUrl(bid, options, 'params'); if (descriptionUrl) { queryParams.description_url = descriptionUrl; } return buildUrl({ protocol: 'https', host: 'securepubads.g.doubleclick.net', pathname: '/gampad/ads', search: queryParams }); }
JavaScript
function buildAdpodVideoUrl({code, params, callback} = {}) { if (!params || !callback) { logError(`A params object and a callback is required to use pbjs.adServers.dfp.buildAdpodVideoUrl`); return; } const derivedParams = { correlator: Date.now(), sz: getSizeForAdUnit(code), url: encodeURIComponent(location.href), }; function getSizeForAdUnit(code) { let adUnit = auctionManager.getAdUnits() .filter((adUnit) => adUnit.code === code) let sizes = deepAccess(adUnit[0], 'mediaTypes.video.playerSize'); return parseSizesInput(sizes).join('|'); } adpodUtils.getTargeting({ 'codes': [code], 'callback': createMasterTag }); function createMasterTag(err, targeting) { if (err) { callback(err, null); return; } let initialValue = { [adpodUtils.TARGETING_KEY_PB_CAT_DUR]: undefined, [adpodUtils.TARGETING_KEY_CACHE_ID]: undefined } let customParams = {}; if (targeting[code]) { customParams = targeting[code].reduce((acc, curValue) => { if (Object.keys(curValue)[0] === adpodUtils.TARGETING_KEY_PB_CAT_DUR) { acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] = (typeof acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] !== 'undefined') ? acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] + ',' + curValue[adpodUtils.TARGETING_KEY_PB_CAT_DUR] : curValue[adpodUtils.TARGETING_KEY_PB_CAT_DUR]; } else if (Object.keys(curValue)[0] === adpodUtils.TARGETING_KEY_CACHE_ID) { acc[adpodUtils.TARGETING_KEY_CACHE_ID] = curValue[adpodUtils.TARGETING_KEY_CACHE_ID] } return acc; }, initialValue); } let encodedCustomParams = encodeURIComponent(formatQS(customParams)); const queryParams = Object.assign({}, defaultParamConstants, derivedParams, params, { cust_params: encodedCustomParams } ); const masterTag = buildUrl({ protocol: 'https', host: 'securepubads.g.doubleclick.net', pathname: '/gampad/ads', search: queryParams }); callback(null, masterTag); } }
function buildAdpodVideoUrl({code, params, callback} = {}) { if (!params || !callback) { logError(`A params object and a callback is required to use pbjs.adServers.dfp.buildAdpodVideoUrl`); return; } const derivedParams = { correlator: Date.now(), sz: getSizeForAdUnit(code), url: encodeURIComponent(location.href), }; function getSizeForAdUnit(code) { let adUnit = auctionManager.getAdUnits() .filter((adUnit) => adUnit.code === code) let sizes = deepAccess(adUnit[0], 'mediaTypes.video.playerSize'); return parseSizesInput(sizes).join('|'); } adpodUtils.getTargeting({ 'codes': [code], 'callback': createMasterTag }); function createMasterTag(err, targeting) { if (err) { callback(err, null); return; } let initialValue = { [adpodUtils.TARGETING_KEY_PB_CAT_DUR]: undefined, [adpodUtils.TARGETING_KEY_CACHE_ID]: undefined } let customParams = {}; if (targeting[code]) { customParams = targeting[code].reduce((acc, curValue) => { if (Object.keys(curValue)[0] === adpodUtils.TARGETING_KEY_PB_CAT_DUR) { acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] = (typeof acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] !== 'undefined') ? acc[adpodUtils.TARGETING_KEY_PB_CAT_DUR] + ',' + curValue[adpodUtils.TARGETING_KEY_PB_CAT_DUR] : curValue[adpodUtils.TARGETING_KEY_PB_CAT_DUR]; } else if (Object.keys(curValue)[0] === adpodUtils.TARGETING_KEY_CACHE_ID) { acc[adpodUtils.TARGETING_KEY_CACHE_ID] = curValue[adpodUtils.TARGETING_KEY_CACHE_ID] } return acc; }, initialValue); } let encodedCustomParams = encodeURIComponent(formatQS(customParams)); const queryParams = Object.assign({}, defaultParamConstants, derivedParams, params, { cust_params: encodedCustomParams } ); const masterTag = buildUrl({ protocol: 'https', host: 'securepubads.g.doubleclick.net', pathname: '/gampad/ads', search: queryParams }); callback(null, masterTag); } }
JavaScript
function buildUrlFromAdserverUrlComponents(components, bid, options) { const descriptionUrl = getDescriptionUrl(bid, components, 'search'); if (descriptionUrl) { components.search.description_url = descriptionUrl; } const encodedCustomParams = getCustParams(bid, options); components.search.cust_params = (components.search.cust_params) ? components.search.cust_params + '%26' + encodedCustomParams : encodedCustomParams; return buildUrl(components); }
function buildUrlFromAdserverUrlComponents(components, bid, options) { const descriptionUrl = getDescriptionUrl(bid, components, 'search'); if (descriptionUrl) { components.search.description_url = descriptionUrl; } const encodedCustomParams = getCustParams(bid, options); components.search.cust_params = (components.search.cust_params) ? components.search.cust_params + '%26' + encodedCustomParams : encodedCustomParams; return buildUrl(components); }
JavaScript
function sendEvent(eventName) { const ts = Date.now(); const eventObject = { t: ts, tse: ts, z: state.zoneId, e: eventName, src: 'pa', puid: state.transactionId, trId: state.transactionId, ver: SUBLIME_VERSION, }; log('Sending pixel for event: ' + eventName, eventObject); const queryString = utils.formatQS(eventObject); utils.triggerPixel('https://' + SUBLIME_ANTENNA + '/?' + queryString); }
function sendEvent(eventName) { const ts = Date.now(); const eventObject = { t: ts, tse: ts, z: state.zoneId, e: eventName, src: 'pa', puid: state.transactionId, trId: state.transactionId, ver: SUBLIME_VERSION, }; log('Sending pixel for event: ' + eventName, eventObject); const queryString = utils.formatQS(eventObject); utils.triggerPixel('https://' + SUBLIME_ANTENNA + '/?' + queryString); }
JavaScript
function buildRequests(validBidRequests, bidderRequest) { const commonPayload = { pbav: SUBLIME_VERSION, // Current Prebid params prebidVersion: '$prebid.version$', currencyCode: config.getConfig('currency.adServerCurrency') || DEFAULT_CURRENCY, timeout: (typeof bidderRequest === 'object' && !!bidderRequest) ? bidderRequest.timeout : config.getConfig('bidderTimeout'), }; // RefererInfo if (bidderRequest && bidderRequest.refererInfo) { commonPayload.referer = bidderRequest.refererInfo.referer; commonPayload.numIframes = bidderRequest.refererInfo.numIframes; } // GDPR handling if (bidderRequest && bidderRequest.gdprConsent) { commonPayload.gdprConsent = bidderRequest.gdprConsent.consentString; commonPayload.gdpr = bidderRequest.gdprConsent.gdprApplies; // we're handling the undefined case server side } return validBidRequests.map(bid => { const bidHost = bid.params.bidHost || DEFAULT_BID_HOST; const protocol = bid.params.protocol || DEFAULT_PROTOCOL; setState({ transactionId: bid.transactionId, zoneId: bid.params.zoneId, debug: bid.params.debug || false, }); const bidPayload = { adUnitCode: bid.adUnitCode, auctionId: bid.auctionId, bidder: bid.bidder, bidderRequestId: bid.bidderRequestId, bidRequestsCount: bid.bidRequestsCount, requestId: bid.bidId, sizes: bid.sizes.map(size => ({ w: size[0], h: size[1], })), transactionId: bid.transactionId, zoneId: bid.params.zoneId, }; const payload = Object.assign({}, commonPayload, bidPayload); return { method: 'POST', url: protocol + '://' + bidHost + '/bid', data: payload, options: { contentType: 'application/json', withCredentials: true }, } }); }
function buildRequests(validBidRequests, bidderRequest) { const commonPayload = { pbav: SUBLIME_VERSION, // Current Prebid params prebidVersion: '$prebid.version$', currencyCode: config.getConfig('currency.adServerCurrency') || DEFAULT_CURRENCY, timeout: (typeof bidderRequest === 'object' && !!bidderRequest) ? bidderRequest.timeout : config.getConfig('bidderTimeout'), }; // RefererInfo if (bidderRequest && bidderRequest.refererInfo) { commonPayload.referer = bidderRequest.refererInfo.referer; commonPayload.numIframes = bidderRequest.refererInfo.numIframes; } // GDPR handling if (bidderRequest && bidderRequest.gdprConsent) { commonPayload.gdprConsent = bidderRequest.gdprConsent.consentString; commonPayload.gdpr = bidderRequest.gdprConsent.gdprApplies; // we're handling the undefined case server side } return validBidRequests.map(bid => { const bidHost = bid.params.bidHost || DEFAULT_BID_HOST; const protocol = bid.params.protocol || DEFAULT_PROTOCOL; setState({ transactionId: bid.transactionId, zoneId: bid.params.zoneId, debug: bid.params.debug || false, }); const bidPayload = { adUnitCode: bid.adUnitCode, auctionId: bid.auctionId, bidder: bid.bidder, bidderRequestId: bid.bidderRequestId, bidRequestsCount: bid.bidRequestsCount, requestId: bid.bidId, sizes: bid.sizes.map(size => ({ w: size[0], h: size[1], })), transactionId: bid.transactionId, zoneId: bid.params.zoneId, }; const payload = Object.assign({}, commonPayload, bidPayload); return { method: 'POST', url: protocol + '://' + bidHost + '/bid', data: payload, options: { contentType: 'application/json', withCredentials: true }, } }); }
JavaScript
function interpretResponse(serverResponse, bidRequest) { const bidResponses = []; const response = serverResponse.body; if (response) { if (response.timeout || !response.ad || /<!--\s+No\s+ad\s+-->/gmi.test(response.ad)) { return bidResponses; } // Setting our returned sizes object to default values let returnedSizes = { width: 1800, height: 1000 }; // Verifying Banner sizes if (bidRequest && bidRequest.data && bidRequest.data.w === 1 && bidRequest.data.h === 1) { // If banner sizes are 1x1 we set our default size object to 1x1 returnedSizes = { width: 1, height: 1 }; } const bidResponse = { requestId: response.requestId || '', cpm: response.cpm || 0, width: response.width || returnedSizes.width, height: response.height || returnedSizes.height, creativeId: response.creativeId || 1, dealId: response.dealId || 1, currency: response.currency || DEFAULT_CURRENCY, netRevenue: response.netRevenue || true, ttl: response.ttl || DEFAULT_TTL, ad: response.ad, pbav: SUBLIME_VERSION }; bidResponses.push(bidResponse); } return bidResponses; }
function interpretResponse(serverResponse, bidRequest) { const bidResponses = []; const response = serverResponse.body; if (response) { if (response.timeout || !response.ad || /<!--\s+No\s+ad\s+-->/gmi.test(response.ad)) { return bidResponses; } // Setting our returned sizes object to default values let returnedSizes = { width: 1800, height: 1000 }; // Verifying Banner sizes if (bidRequest && bidRequest.data && bidRequest.data.w === 1 && bidRequest.data.h === 1) { // If banner sizes are 1x1 we set our default size object to 1x1 returnedSizes = { width: 1, height: 1 }; } const bidResponse = { requestId: response.requestId || '', cpm: response.cpm || 0, width: response.width || returnedSizes.width, height: response.height || returnedSizes.height, creativeId: response.creativeId || 1, dealId: response.dealId || 1, currency: response.currency || DEFAULT_CURRENCY, netRevenue: response.netRevenue || true, ttl: response.ttl || DEFAULT_TTL, ad: response.ad, pbav: SUBLIME_VERSION }; bidResponses.push(bidResponse); } return bidResponses; }
JavaScript
function buildGiBidRequest(bidRequest) { let giBidRequest = { bid_id: bidRequest.bidId, pid: bidRequest.params.pid, // required tid: bidRequest.params.tid, // required known: bidRequest.params.known || 1, is_video: bidRequest.mediaType === 'video', resp_type: 'JSON', provider: 'direct.prebidjs' }; if (bidRequest.sizes) { giBidRequest.size = produceSize(bidRequest.sizes); } addVideo(bidRequest.params.video, giBidRequest); addOptional(bidRequest.params, giBidRequest, OPTIONAL_PROPERTIES); return giBidRequest; }
function buildGiBidRequest(bidRequest) { let giBidRequest = { bid_id: bidRequest.bidId, pid: bidRequest.params.pid, // required tid: bidRequest.params.tid, // required known: bidRequest.params.known || 1, is_video: bidRequest.mediaType === 'video', resp_type: 'JSON', provider: 'direct.prebidjs' }; if (bidRequest.sizes) { giBidRequest.size = produceSize(bidRequest.sizes); } addVideo(bidRequest.params.video, giBidRequest); addOptional(bidRequest.params, giBidRequest, OPTIONAL_PROPERTIES); return giBidRequest; }
JavaScript
function produceSize (sizes) { function sizeToStr(s) { if (Array.isArray(s) && s.length === 2 && isInteger(s[0]) && isInteger(s[1])) { return s.join('x'); } else { throw "Malformed parameter 'sizes'"; } } if (Array.isArray(sizes) && Array.isArray(sizes[0])) { return sizes.map(sizeToStr).join(','); } else { return sizeToStr(sizes); } }
function produceSize (sizes) { function sizeToStr(s) { if (Array.isArray(s) && s.length === 2 && isInteger(s[0]) && isInteger(s[1])) { return s.join('x'); } else { throw "Malformed parameter 'sizes'"; } } if (Array.isArray(sizes) && Array.isArray(sizes[0])) { return sizes.map(sizeToStr).join(','); } else { return sizeToStr(sizes); } }
JavaScript
function validateProviderDataForGPT(data) { // data must be an object, contains object with string as value if (typeof data !== 'object') { return {}; } for (let key in data) { if (data.hasOwnProperty(key)) { for (let innerKey in data[key]) { if (data[key].hasOwnProperty(innerKey)) { if (typeof data[key][innerKey] !== 'string') { utils.logWarn(`removing ${key}: {${innerKey}:${data[key][innerKey]} } from GPT targeting because of invalid type (must be string)`); delete data[key][innerKey]; } } } } } return data; }
function validateProviderDataForGPT(data) { // data must be an object, contains object with string as value if (typeof data !== 'object') { return {}; } for (let key in data) { if (data.hasOwnProperty(key)) { for (let innerKey in data[key]) { if (data[key].hasOwnProperty(innerKey)) { if (typeof data[key][innerKey] !== 'string') { utils.logWarn(`removing ${key}: {${innerKey}:${data[key][innerKey]} } from GPT targeting because of invalid type (must be string)`); delete data[key][innerKey]; } } } } } return data; }
JavaScript
function requestBidsHook(fn, reqBidsConfigObj) { getProviderData(reqBidsConfigObj.adUnits || getGlobal().adUnits, (data) => { if (data && Object.keys(data).length) { const _mergedData = deepMerge(data); if (Object.keys(_mergedData).length) { setDataForPrimaryAdServer(_mergedData); addIdDataToAdUnitBids(reqBidsConfigObj.adUnits || getGlobal().adUnits, _mergedData); } } return fn.call(this, reqBidsConfigObj); }); }
function requestBidsHook(fn, reqBidsConfigObj) { getProviderData(reqBidsConfigObj.adUnits || getGlobal().adUnits, (data) => { if (data && Object.keys(data).length) { const _mergedData = deepMerge(data); if (Object.keys(_mergedData).length) { setDataForPrimaryAdServer(_mergedData); addIdDataToAdUnitBids(reqBidsConfigObj.adUnits || getGlobal().adUnits, _mergedData); } } return fn.call(this, reqBidsConfigObj); }); }
JavaScript
function bidShouldBeAddedToTargeting(bid, adUnitCodes) { return bid.adserverTargeting && adUnitCodes && ((utils.isArray(adUnitCodes) && includes(adUnitCodes, bid.adUnitCode)) || (typeof adUnitCodes === 'string' && bid.adUnitCode === adUnitCodes)); }
function bidShouldBeAddedToTargeting(bid, adUnitCodes) { return bid.adserverTargeting && adUnitCodes && ((utils.isArray(adUnitCodes) && includes(adUnitCodes, bid.adUnitCode)) || (typeof adUnitCodes === 'string' && bid.adUnitCode === adUnitCodes)); }
JavaScript
function mergeAdServerTargeting(acc, bid, index, arr) { function concatTargetingValue(key) { return function(currentBidElement) { if (!utils.isArray(currentBidElement.adserverTargeting[key])) { currentBidElement.adserverTargeting[key] = [currentBidElement.adserverTargeting[key]]; } currentBidElement.adserverTargeting[key] = currentBidElement.adserverTargeting[key].concat(bid.adserverTargeting[key]).filter(uniques); delete bid.adserverTargeting[key]; } } function hasSameAdunitCodeAndKey(key) { return function(currentBidElement) { return currentBidElement.adUnitCode === bid.adUnitCode && currentBidElement.adserverTargeting[key] } } Object.keys(bid.adserverTargeting) .filter(getCustomKeys()) .forEach(key => { if (acc.length) { acc.filter(hasSameAdunitCodeAndKey(key)) .forEach(concatTargetingValue(key)); } }); acc.push(bid); return acc; }
function mergeAdServerTargeting(acc, bid, index, arr) { function concatTargetingValue(key) { return function(currentBidElement) { if (!utils.isArray(currentBidElement.adserverTargeting[key])) { currentBidElement.adserverTargeting[key] = [currentBidElement.adserverTargeting[key]]; } currentBidElement.adserverTargeting[key] = currentBidElement.adserverTargeting[key].concat(bid.adserverTargeting[key]).filter(uniques); delete bid.adserverTargeting[key]; } } function hasSameAdunitCodeAndKey(key) { return function(currentBidElement) { return currentBidElement.adUnitCode === bid.adUnitCode && currentBidElement.adserverTargeting[key] } } Object.keys(bid.adserverTargeting) .filter(getCustomKeys()) .forEach(key => { if (acc.length) { acc.filter(hasSameAdunitCodeAndKey(key)) .forEach(concatTargetingValue(key)); } }); acc.push(bid); return acc; }
JavaScript
function newBid(serverBid, creativeBid, bidderRequest) { const bid = { requestId: serverBid.slotId, creativeId: creativeBid.adId, network: serverBid.network, adType: creativeBid.creativeDetails.type, dealId: 99999999, currency: 'USD', netRevenue: true, ttl: 300 }; if (creativeBid.creativeDetails.type === 'VAST') { Object.assign(bid, { width: creativeBid.width, height: creativeBid.height, vastXml: creativeBid.creativeDetails.adContent, cpm: parseInt(creativeBid.bidCpm) / 1000000, ttl: 3600 }); const rendererOptions = utils.deepAccess( bidderRequest, 'renderer.options' ); let rendererUrl = 'https://ss3.zedo.com/gecko/beta/fmpbgt.min.js'; Object.assign(bid, { adResponse: serverBid, renderer: getRenderer(bid.adUnitCode, serverBid.slotId, rendererUrl, rendererOptions) }); } else { Object.assign(bid, { width: creativeBid.width, height: creativeBid.height, cpm: parseInt(creativeBid.bidCpm) / 1000000, ad: creativeBid.creativeDetails.adContent, }); } return bid; }
function newBid(serverBid, creativeBid, bidderRequest) { const bid = { requestId: serverBid.slotId, creativeId: creativeBid.adId, network: serverBid.network, adType: creativeBid.creativeDetails.type, dealId: 99999999, currency: 'USD', netRevenue: true, ttl: 300 }; if (creativeBid.creativeDetails.type === 'VAST') { Object.assign(bid, { width: creativeBid.width, height: creativeBid.height, vastXml: creativeBid.creativeDetails.adContent, cpm: parseInt(creativeBid.bidCpm) / 1000000, ttl: 3600 }); const rendererOptions = utils.deepAccess( bidderRequest, 'renderer.options' ); let rendererUrl = 'https://ss3.zedo.com/gecko/beta/fmpbgt.min.js'; Object.assign(bid, { adResponse: serverBid, renderer: getRenderer(bid.adUnitCode, serverBid.slotId, rendererUrl, rendererOptions) }); } else { Object.assign(bid, { width: creativeBid.width, height: creativeBid.height, cpm: parseInt(creativeBid.bidCpm) / 1000000, ad: creativeBid.creativeDetails.adContent, }); } return bid; }
JavaScript
function registerVideoSupport(name, videoSupport) { prebid.adServers = prebid.adServers || { }; prebid.adServers[name] = prebid.adServers[name] || { }; Object.keys(videoSupport).forEach((key) => { if (prebid.adServers[name][key]) { logWarn(`Attempting to add an already registered function property ${key} for AdServer ${name}.`); return; } prebid.adServers[name][key] = videoSupport[key]; }); }
function registerVideoSupport(name, videoSupport) { prebid.adServers = prebid.adServers || { }; prebid.adServers[name] = prebid.adServers[name] || { }; Object.keys(videoSupport).forEach((key) => { if (prebid.adServers[name][key]) { logWarn(`Attempting to add an already registered function property ${key} for AdServer ${name}.`); return; } prebid.adServers[name][key] = videoSupport[key]; }); }
JavaScript
function bidToBannerImp(bid) { const imp = bidToImp(bid); imp.banner = {}; imp.banner.w = bid.params.size[0]; imp.banner.h = bid.params.size[1]; imp.banner.topframe = utils.inIframe() ? 0 : 1; return imp; }
function bidToBannerImp(bid) { const imp = bidToImp(bid); imp.banner = {}; imp.banner.w = bid.params.size[0]; imp.banner.h = bid.params.size[1]; imp.banner.topframe = utils.inIframe() ? 0 : 1; return imp; }
JavaScript
function bidToVideoImp(bid) { const imp = bidToImp(bid); imp.video = utils.deepClone(bid.params.video) imp.video.w = bid.params.size[0]; imp.video.h = bid.params.size[1]; const context = utils.deepAccess(bid, 'mediaTypes.video.context'); if (context) { if (context === 'instream') { imp.video.placement = 1; } else if (context === 'outstream') { imp.video.placement = 4; } else { utils.logWarn(`ix bidder params: video context '${context}' is not supported`); } } return imp; }
function bidToVideoImp(bid) { const imp = bidToImp(bid); imp.video = utils.deepClone(bid.params.video) imp.video.w = bid.params.size[0]; imp.video.h = bid.params.size[1]; const context = utils.deepAccess(bid, 'mediaTypes.video.context'); if (context) { if (context === 'instream') { imp.video.placement = 1; } else if (context === 'outstream') { imp.video.placement = 4; } else { utils.logWarn(`ix bidder params: video context '${context}' is not supported`); } } return imp; }
JavaScript
function includesSize(sizeArray, size) { if (isValidSize(sizeArray)) { return sizeArray[0] === size[0] && sizeArray[1] === size[1]; } for (let i = 0; i < sizeArray.length; i++) { if (sizeArray[i][0] === size[0] && sizeArray[i][1] === size[1]) { return true; } } return false; }
function includesSize(sizeArray, size) { if (isValidSize(sizeArray)) { return sizeArray[0] === size[0] && sizeArray[1] === size[1]; } for (let i = 0; i < sizeArray.length; i++) { if (sizeArray[i][0] === size[0] && sizeArray[i][1] === size[1]) { return true; } } return false; }
JavaScript
function buildRequest(validBidRequests, bidderRequest, impressions, version) { const userEids = []; // Always use secure HTTPS protocol. let baseUrl = SECURE_BID_URL; // RTI ids will be included in the bid request if the function getIdentityInfo() is loaded // and if the data for the partner exist if (window.headertag && typeof window.headertag.getIdentityInfo === 'function') { let identityInfo = window.headertag.getIdentityInfo(); if (identityInfo && typeof identityInfo === 'object') { for (const partnerName in identityInfo) { if (identityInfo.hasOwnProperty(partnerName)) { let response = identityInfo[partnerName]; if (!response.responsePending && response.data && typeof response.data === 'object' && Object.keys(response.data).length) { userEids.push(response.data); } } } } } const r = {}; // Since bidderRequestId are the same for different bid request, just use the first one. r.id = validBidRequests[0].bidderRequestId; r.imp = impressions; r.site = {}; r.ext = {}; r.ext.source = 'prebid'; // if an schain is provided, send it along if (validBidRequests[0].schain) { r.source = { ext: { schain: validBidRequests[0].schain } }; } if (userEids.length > 0) { r.user = {}; r.user.eids = userEids; } if (document.referrer && document.referrer !== '') { r.site.ref = document.referrer; } // Apply GDPR information to the request if GDPR is enabled. if (bidderRequest) { if (bidderRequest.gdprConsent) { const gdprConsent = bidderRequest.gdprConsent; if (gdprConsent.hasOwnProperty('gdprApplies')) { r.regs = { ext: { gdpr: gdprConsent.gdprApplies ? 1 : 0 } }; } if (gdprConsent.hasOwnProperty('consentString')) { r.user = r.user || {}; r.user.ext = { consent: gdprConsent.consentString || '' }; } } if (bidderRequest.uspConsent) { utils.deepSetValue(r, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (bidderRequest.refererInfo) { r.site.page = bidderRequest.refererInfo.referer; } } const payload = {}; // Parse additional runtime configs. const bidderCode = (bidderRequest && bidderRequest.bidderCode) || 'ix'; const otherIxConfig = config.getConfig(bidderCode); if (otherIxConfig) { // Append firstPartyData to r.site.page if firstPartyData exists. if (typeof otherIxConfig.firstPartyData === 'object') { const firstPartyData = otherIxConfig.firstPartyData; let firstPartyString = '?'; for (const key in firstPartyData) { if (firstPartyData.hasOwnProperty(key)) { firstPartyString += `${encodeURIComponent(key)}=${encodeURIComponent(firstPartyData[key])}&`; } } firstPartyString = firstPartyString.slice(0, -1); r.site.page += firstPartyString; } // Create t in payload if timeout is configured. if (typeof otherIxConfig.timeout === 'number') { payload.t = otherIxConfig.timeout; } } // Use the siteId in the first bid request as the main siteId. payload.s = validBidRequests[0].params.siteId; payload.v = version; payload.r = JSON.stringify(r); payload.ac = 'j'; payload.sd = 1; if (version === VIDEO_ENDPOINT_VERSION) { payload.nf = 1; } return { method: 'GET', url: baseUrl, data: payload }; }
function buildRequest(validBidRequests, bidderRequest, impressions, version) { const userEids = []; // Always use secure HTTPS protocol. let baseUrl = SECURE_BID_URL; // RTI ids will be included in the bid request if the function getIdentityInfo() is loaded // and if the data for the partner exist if (window.headertag && typeof window.headertag.getIdentityInfo === 'function') { let identityInfo = window.headertag.getIdentityInfo(); if (identityInfo && typeof identityInfo === 'object') { for (const partnerName in identityInfo) { if (identityInfo.hasOwnProperty(partnerName)) { let response = identityInfo[partnerName]; if (!response.responsePending && response.data && typeof response.data === 'object' && Object.keys(response.data).length) { userEids.push(response.data); } } } } } const r = {}; // Since bidderRequestId are the same for different bid request, just use the first one. r.id = validBidRequests[0].bidderRequestId; r.imp = impressions; r.site = {}; r.ext = {}; r.ext.source = 'prebid'; // if an schain is provided, send it along if (validBidRequests[0].schain) { r.source = { ext: { schain: validBidRequests[0].schain } }; } if (userEids.length > 0) { r.user = {}; r.user.eids = userEids; } if (document.referrer && document.referrer !== '') { r.site.ref = document.referrer; } // Apply GDPR information to the request if GDPR is enabled. if (bidderRequest) { if (bidderRequest.gdprConsent) { const gdprConsent = bidderRequest.gdprConsent; if (gdprConsent.hasOwnProperty('gdprApplies')) { r.regs = { ext: { gdpr: gdprConsent.gdprApplies ? 1 : 0 } }; } if (gdprConsent.hasOwnProperty('consentString')) { r.user = r.user || {}; r.user.ext = { consent: gdprConsent.consentString || '' }; } } if (bidderRequest.uspConsent) { utils.deepSetValue(r, 'regs.ext.us_privacy', bidderRequest.uspConsent); } if (bidderRequest.refererInfo) { r.site.page = bidderRequest.refererInfo.referer; } } const payload = {}; // Parse additional runtime configs. const bidderCode = (bidderRequest && bidderRequest.bidderCode) || 'ix'; const otherIxConfig = config.getConfig(bidderCode); if (otherIxConfig) { // Append firstPartyData to r.site.page if firstPartyData exists. if (typeof otherIxConfig.firstPartyData === 'object') { const firstPartyData = otherIxConfig.firstPartyData; let firstPartyString = '?'; for (const key in firstPartyData) { if (firstPartyData.hasOwnProperty(key)) { firstPartyString += `${encodeURIComponent(key)}=${encodeURIComponent(firstPartyData[key])}&`; } } firstPartyString = firstPartyString.slice(0, -1); r.site.page += firstPartyString; } // Create t in payload if timeout is configured. if (typeof otherIxConfig.timeout === 'number') { payload.t = otherIxConfig.timeout; } } // Use the siteId in the first bid request as the main siteId. payload.s = validBidRequests[0].params.siteId; payload.v = version; payload.r = JSON.stringify(r); payload.ac = 'j'; payload.sd = 1; if (version === VIDEO_ENDPOINT_VERSION) { payload.nf = 1; } return { method: 'GET', url: baseUrl, data: payload }; }
JavaScript
function callApi(options) { var ajaxOptions = { method: 'GET', withCredentials: true }; ajax( DT_ID_SVC, { success: options.success, error: options.fail }, null, ajaxOptions ); }
function callApi(options) { var ajaxOptions = { method: 'GET', withCredentials: true }; ajax( DT_ID_SVC, { success: options.success, error: options.fail }, null, ajaxOptions ); }
JavaScript
function writeDigiId(id) { var key = 'DigiTrust.v1.identity'; var date = new Date(); date.setTime(date.getTime() + 604800000); storage.setCookie(key, encId(id), date.toUTCString(), 'none'); }
function writeDigiId(id) { var key = 'DigiTrust.v1.identity'; var date = new Date(); date.setTime(date.getTime() + 604800000); storage.setCookie(key, encId(id), date.toUTCString(), 'none'); }
JavaScript
function isFirefoxBrowser(ua) { ua = ua || navigator.userAgent; ua = ua.toLowerCase(); if (ua.indexOf('firefox') !== -1) { return true; } return false; }
function isFirefoxBrowser(ua) { ua = ua || navigator.userAgent; ua = ua.toLowerCase(); if (ua.indexOf('firefox') !== -1) { return true; } return false; }
JavaScript
function isDisallowedBrowserForApiCall() { if (utils.isSafariBrowser()) { return true; } else if (isFirefoxBrowser()) { return true; } return false; }
function isDisallowedBrowserForApiCall() { if (utils.isSafariBrowser()) { return true; } else if (isFirefoxBrowser()) { return true; } return false; }
JavaScript
function initDigitrustFacade(config) { clearTimeout(fallbackTimer); fallbackTimer = 0; var facade = { isClient: true, isMock: true, _internals: { callCount: 0, initCallback: null }, getUser: function (obj, callback) { var isAsync = !!isFunc(callback); var cb = isAsync ? callback : noop; var errResp = { success: false }; var inter = facade._internals; inter.callCount++; // wrap the initializer callback, if present var checkAndCallInitializeCb = function (idResponse) { if (inter.callCount <= 1 && isFunc(inter.initCallback)) { try { inter.initCallback(idResponse); } catch (ex) { utils.logError('Exception in passed DigiTrust init callback', ex); } } } if (!isMemberIdValid(obj.member)) { if (!isAsync) { return errResp } else { cb(errResp); return; } } if (_savedId != null) { if (isAsync) { checkAndCallInitializeCb(_savedId); // cb(_savedId); return; } else { return _savedId; } } var opts = { success: function (respText, result) { var idResult = { success: true } try { idResult.identity = JSON.parse(respText); _savedId = idResult; // Save result to the cache variable writeDigiId(respText); } catch (ex) { idResult.success = false; delete idResult.identity; } checkAndCallInitializeCb(idResult); }, fail: function (statusErr, result) { utils.logError('DigiTrustId API error: ' + statusErr); } } // check gdpr vendor here. Full DigiTrust library has vendor check built in gdprConsent.hasConsent(null, function (hasConsent) { if (hasConsent) { if (isDisallowedBrowserForApiCall()) { let resultObj = { success: false, err: 'Your browser does not support DigiTrust Identity' } checkAndCallInitializeCb(resultObj); return; } callApi(opts); } }) if (!isAsync) { return errResp; // even if it will be successful later, without a callback we report a "failure in this moment" } } } if (config && isFunc(config.callback)) { facade._internals.initCallback = config.callback; } if (window && window.DigiTrust == null) { window.DigiTrust = facade; } }
function initDigitrustFacade(config) { clearTimeout(fallbackTimer); fallbackTimer = 0; var facade = { isClient: true, isMock: true, _internals: { callCount: 0, initCallback: null }, getUser: function (obj, callback) { var isAsync = !!isFunc(callback); var cb = isAsync ? callback : noop; var errResp = { success: false }; var inter = facade._internals; inter.callCount++; // wrap the initializer callback, if present var checkAndCallInitializeCb = function (idResponse) { if (inter.callCount <= 1 && isFunc(inter.initCallback)) { try { inter.initCallback(idResponse); } catch (ex) { utils.logError('Exception in passed DigiTrust init callback', ex); } } } if (!isMemberIdValid(obj.member)) { if (!isAsync) { return errResp } else { cb(errResp); return; } } if (_savedId != null) { if (isAsync) { checkAndCallInitializeCb(_savedId); // cb(_savedId); return; } else { return _savedId; } } var opts = { success: function (respText, result) { var idResult = { success: true } try { idResult.identity = JSON.parse(respText); _savedId = idResult; // Save result to the cache variable writeDigiId(respText); } catch (ex) { idResult.success = false; delete idResult.identity; } checkAndCallInitializeCb(idResult); }, fail: function (statusErr, result) { utils.logError('DigiTrustId API error: ' + statusErr); } } // check gdpr vendor here. Full DigiTrust library has vendor check built in gdprConsent.hasConsent(null, function (hasConsent) { if (hasConsent) { if (isDisallowedBrowserForApiCall()) { let resultObj = { success: false, err: 'Your browser does not support DigiTrust Identity' } checkAndCallInitializeCb(resultObj); return; } callApi(opts); } }) if (!isAsync) { return errResp; // even if it will be successful later, without a callback we report a "failure in this moment" } } } if (config && isFunc(config.callback)) { facade._internals.initCallback = config.callback; } if (window && window.DigiTrust == null) { window.DigiTrust = facade; } }
JavaScript
function wrapIdResult() { if (me.idObj == null) { me.idObj = _savedId; } if (me.idObj == null) { return null; } var cp = me.configParams; var exp = (cp && cp.storage && cp.storage.expires) || 60; var rslt = { data: null, expires: exp }; if (me.idObj && me.idObj.success && me.idObj.identity) { rslt.data = me.idObj.identity; } else { rslt.err = 'Failure getting id'; } return rslt; }
function wrapIdResult() { if (me.idObj == null) { me.idObj = _savedId; } if (me.idObj == null) { return null; } var cp = me.configParams; var exp = (cp && cp.storage && cp.storage.expires) || 60; var rslt = { data: null, expires: exp }; if (me.idObj && me.idObj.success && me.idObj.identity) { rslt.data = me.idObj.identity; } else { rslt.err = 'Failure getting id'; } return rslt; }
JavaScript
function fallbackInit() { if (resultHandler.retryId == 0 && !isInitialized()) { // this triggers an init var conf = { member: 'fallback', callback: noop }; getDigiTrustId(conf); } }
function fallbackInit() { if (resultHandler.retryId == 0 && !isInitialized()) { // this triggers an init var conf = { member: 'fallback', callback: noop }; getDigiTrustId(conf); } }
JavaScript
function buildRtbRequest(imps, bidderRequest) { let {bidderCode, gdprConsent, auctionId, refererInfo, timeout, uspConsent} = bidderRequest; let req = { 'id': auctionId, 'imp': imps, 'site': createSite(refererInfo), 'at': 1, 'device': { 'ip': 'caller', 'ua': 'caller', 'js': 1, 'language': getLanguage() }, 'tmax': parseInt(timeout) }; if (utils.getDNT()) { req.device.dnt = 1; } if (gdprConsent) { if (gdprConsent.gdprApplies !== undefined) { utils.deepSetValue(req, 'regs.ext.gdpr', ~~gdprConsent.gdprApplies); } if (gdprConsent.consentString !== undefined) { utils.deepSetValue(req, 'user.ext.consent', gdprConsent.consentString); } } if (uspConsent) { utils.deepSetValue(req, 'regs.ext.us_privacy', uspConsent); } let syncMethod = getAllowedSyncMethod(bidderCode); if (syncMethod) { utils.deepSetValue(req, 'ext.adk_usersync', syncMethod); } return req; }
function buildRtbRequest(imps, bidderRequest) { let {bidderCode, gdprConsent, auctionId, refererInfo, timeout, uspConsent} = bidderRequest; let req = { 'id': auctionId, 'imp': imps, 'site': createSite(refererInfo), 'at': 1, 'device': { 'ip': 'caller', 'ua': 'caller', 'js': 1, 'language': getLanguage() }, 'tmax': parseInt(timeout) }; if (utils.getDNT()) { req.device.dnt = 1; } if (gdprConsent) { if (gdprConsent.gdprApplies !== undefined) { utils.deepSetValue(req, 'regs.ext.gdpr', ~~gdprConsent.gdprApplies); } if (gdprConsent.consentString !== undefined) { utils.deepSetValue(req, 'user.ext.consent', gdprConsent.consentString); } } if (uspConsent) { utils.deepSetValue(req, 'regs.ext.us_privacy', uspConsent); } let syncMethod = getAllowedSyncMethod(bidderCode); if (syncMethod) { utils.deepSetValue(req, 'ext.adk_usersync', syncMethod); } return req; }
JavaScript
isBidRequestValid(bid) { utils.logInfo('OZONE: isBidRequestValid : ', config.getConfig(), bid); let adUnitCode = bid.adUnitCode; // adunit[n].code if (!(bid.params.hasOwnProperty('placementId'))) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : missing placementId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!this.isValidPlacementId(bid.params.placementId)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : placementId must be exactly 10 numeric characters', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('publisherId'))) { utils.logError('OZONE: OZONE BID ADAPTER 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('OZONE: OZONE BID ADAPTER VALIDATION FAILED : publisherId must be exactly 12 alphanumieric characters including hyphens', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('siteId'))) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : missing siteId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!(bid.params.siteId).toString().match(/^[0-9]{10}$/)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : siteId must be exactly 10 numeric characters', adUnitCode); return false; } if (bid.params.hasOwnProperty('customParams')) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customParams should be renamed to customData', adUnitCode); return false; } if (bid.params.hasOwnProperty('customData')) { if (!Array.isArray(bid.params.customData)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData is not an Array', adUnitCode); return false; } if (bid.params.customData.length < 1) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData is an array but does not contain any elements', adUnitCode); return false; } if (!(bid.params.customData[0]).hasOwnProperty('targeting')) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData[0] does not contain "targeting"', adUnitCode); return false; } if (typeof bid.params.customData[0]['targeting'] != 'object') { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData[0] targeting is not an object', adUnitCode); return false; } } if (bid.params.hasOwnProperty('lotameData')) { if (typeof bid.params.lotameData !== 'object') { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : lotameData is not an object', adUnitCode); return false; } } if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('context')) { utils.logError('OZONE: No context key/value in bid. Rejecting bid: ', bid); return false; } if (bid.mediaTypes[VIDEO].context === 'instream') { utils.logWarn('OZONE: video.context instream is not supported. Only outstream video is supported. Video will not be used for Bid: ', bid); } else if (bid.mediaTypes.video.context !== 'outstream') { utils.logError('OZONE: video.context is invalid. Only outstream video is supported. Rejecting bid: ', bid); return false; } } // guard against hacks in GET parameters that we might allow const arrLotameOverride = this.getLotameOverrideParams(); // lotame override, test params. All 3 must be present, or none. let lotameKeys = Object.keys(arrLotameOverride); if (lotameKeys.length === ALLOWED_LOTAME_PARAMS.length) { utils.logInfo('OZONE: VALIDATION : arrLotameOverride', arrLotameOverride); for (let i in lotameKeys) { if (!arrLotameOverride[ALLOWED_LOTAME_PARAMS[i]].toString().match(/^[0-9a-zA-Z]+$/)) { utils.logError('OZONE: Only letters & numbers allowed in lotame override: ' + i.toString() + ': ' + arrLotameOverride[ALLOWED_LOTAME_PARAMS[i]].toString() + '. Rejecting bid: ', bid); return false; } } } else if (lotameKeys.length > 0) { utils.logInfo('OZONE: VALIDATION : arrLotameOverride', arrLotameOverride); utils.logError('OZONE: lotame override params are incomplete. You must set all ' + ALLOWED_LOTAME_PARAMS.length + ': ' + JSON.stringify(ALLOWED_LOTAME_PARAMS) + ', . Rejecting bid: ', bid); return false; } return true; }
isBidRequestValid(bid) { utils.logInfo('OZONE: isBidRequestValid : ', config.getConfig(), bid); let adUnitCode = bid.adUnitCode; // adunit[n].code if (!(bid.params.hasOwnProperty('placementId'))) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : missing placementId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!this.isValidPlacementId(bid.params.placementId)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : placementId must be exactly 10 numeric characters', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('publisherId'))) { utils.logError('OZONE: OZONE BID ADAPTER 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('OZONE: OZONE BID ADAPTER VALIDATION FAILED : publisherId must be exactly 12 alphanumieric characters including hyphens', adUnitCode); return false; } if (!(bid.params.hasOwnProperty('siteId'))) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : missing siteId : siteId, placementId and publisherId are REQUIRED', adUnitCode); return false; } if (!(bid.params.siteId).toString().match(/^[0-9]{10}$/)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : siteId must be exactly 10 numeric characters', adUnitCode); return false; } if (bid.params.hasOwnProperty('customParams')) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customParams should be renamed to customData', adUnitCode); return false; } if (bid.params.hasOwnProperty('customData')) { if (!Array.isArray(bid.params.customData)) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData is not an Array', adUnitCode); return false; } if (bid.params.customData.length < 1) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData is an array but does not contain any elements', adUnitCode); return false; } if (!(bid.params.customData[0]).hasOwnProperty('targeting')) { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData[0] does not contain "targeting"', adUnitCode); return false; } if (typeof bid.params.customData[0]['targeting'] != 'object') { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : customData[0] targeting is not an object', adUnitCode); return false; } } if (bid.params.hasOwnProperty('lotameData')) { if (typeof bid.params.lotameData !== 'object') { utils.logError('OZONE: OZONE BID ADAPTER VALIDATION FAILED : lotameData is not an object', adUnitCode); return false; } } if (bid.hasOwnProperty('mediaTypes') && bid.mediaTypes.hasOwnProperty(VIDEO)) { if (!bid.mediaTypes[VIDEO].hasOwnProperty('context')) { utils.logError('OZONE: No context key/value in bid. Rejecting bid: ', bid); return false; } if (bid.mediaTypes[VIDEO].context === 'instream') { utils.logWarn('OZONE: video.context instream is not supported. Only outstream video is supported. Video will not be used for Bid: ', bid); } else if (bid.mediaTypes.video.context !== 'outstream') { utils.logError('OZONE: video.context is invalid. Only outstream video is supported. Rejecting bid: ', bid); return false; } } // guard against hacks in GET parameters that we might allow const arrLotameOverride = this.getLotameOverrideParams(); // lotame override, test params. All 3 must be present, or none. let lotameKeys = Object.keys(arrLotameOverride); if (lotameKeys.length === ALLOWED_LOTAME_PARAMS.length) { utils.logInfo('OZONE: VALIDATION : arrLotameOverride', arrLotameOverride); for (let i in lotameKeys) { if (!arrLotameOverride[ALLOWED_LOTAME_PARAMS[i]].toString().match(/^[0-9a-zA-Z]+$/)) { utils.logError('OZONE: Only letters & numbers allowed in lotame override: ' + i.toString() + ': ' + arrLotameOverride[ALLOWED_LOTAME_PARAMS[i]].toString() + '. Rejecting bid: ', bid); return false; } } } else if (lotameKeys.length > 0) { utils.logInfo('OZONE: VALIDATION : arrLotameOverride', arrLotameOverride); utils.logError('OZONE: lotame override params are incomplete. You must set all ' + ALLOWED_LOTAME_PARAMS.length + ': ' + JSON.stringify(ALLOWED_LOTAME_PARAMS) + ', . Rejecting bid: ', bid); return false; } return true; }
JavaScript
interpretResponse(serverResponse, request) { utils.logInfo('OZONE: interpretResponse: serverResponse, request', serverResponse, 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')) { return []; } if (typeof serverResponse.seatbid !== 'object') { return []; } let arrAllBids = []; let enhancedAdserverTargeting = config.getConfig('ozone.enhancedAdserverTargeting'); utils.logInfo('OZONE: enhancedAdserverTargeting', enhancedAdserverTargeting); if (typeof enhancedAdserverTargeting == 'undefined') { enhancedAdserverTargeting = true; } utils.logInfo('OZONE: enhancedAdserverTargeting', enhancedAdserverTargeting); serverResponse.seatbid = injectAdIdsIntoAllBidResponses(serverResponse.seatbid); // we now make sure that each bid in the bidresponse has a unique (within page) adId attribute. for (let i = 0; i < serverResponse.seatbid.length; i++) { let sb = serverResponse.seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { const {defaultWidth, defaultHeight} = defaultSize(request.bidderRequest.bids[j]); let thisBid = ozoneAddStandardProperties(sb.bid[j], defaultWidth, defaultHeight); // from https://github.com/prebid/Prebid.js/pull/1082 if (utils.deepAccess(thisBid, 'ext.prebid.type') === VIDEO) { utils.logInfo('OZONE: going to attach a renderer to:', j); let renderConf = createObjectForInternalVideoRender(thisBid); thisBid.renderer = Renderer.install(renderConf); } else { utils.logInfo('OZONE: bid is not a video, will not attach a renderer: ', j); } let ozoneInternalKey = thisBid.bidId; let adserverTargeting = {}; if (enhancedAdserverTargeting) { let allBidsForThisBidid = ozoneGetAllBidsForBidId(ozoneInternalKey, serverResponse.seatbid); // add all the winning & non-winning bids for this bidId: utils.logInfo('OZONE: Going to iterate allBidsForThisBidId', allBidsForThisBidid); Object.keys(allBidsForThisBidid).forEach(function (bidderName, index, ar2) { adserverTargeting['oz_' + bidderName] = bidderName; adserverTargeting['oz_' + bidderName + '_pb'] = String(allBidsForThisBidid[bidderName].price); adserverTargeting['oz_' + bidderName + '_crid'] = String(allBidsForThisBidid[bidderName].crid); adserverTargeting['oz_' + bidderName + '_adv'] = String(allBidsForThisBidid[bidderName].adomain); adserverTargeting['oz_' + bidderName + '_imp_id'] = String(allBidsForThisBidid[bidderName].impid); adserverTargeting['oz_' + bidderName + '_adId'] = String(allBidsForThisBidid[bidderName].adId); adserverTargeting['oz_' + bidderName + '_pb_r'] = getRoundedBid(allBidsForThisBidid[bidderName].price, allBidsForThisBidid[bidderName].ext.prebid.type); if (allBidsForThisBidid[bidderName].hasOwnProperty('dealid')) { adserverTargeting['oz_' + bidderName + '_dealid'] = String(allBidsForThisBidid[bidderName].dealid); } }); } // also add in the winning bid, to be sent to dfp let {seat: winningSeat, bid: winningBid} = ozoneGetWinnerForRequestBid(ozoneInternalKey, serverResponse.seatbid); adserverTargeting['oz_auc_id'] = String(request.bidderRequest.auctionId); adserverTargeting['oz_winner'] = String(winningSeat); adserverTargeting['oz_response_id'] = String(serverResponse.id); if (enhancedAdserverTargeting) { adserverTargeting['oz_winner_auc_id'] = String(winningBid.id); adserverTargeting['oz_winner_imp_id'] = String(winningBid.impid); adserverTargeting['oz_pb_v'] = OZONEVERSION; } thisBid.adserverTargeting = adserverTargeting; arrAllBids.push(thisBid); } } utils.logInfo('OZONE: interpretResponse going to return', arrAllBids); return arrAllBids; }
interpretResponse(serverResponse, request) { utils.logInfo('OZONE: interpretResponse: serverResponse, request', serverResponse, 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')) { return []; } if (typeof serverResponse.seatbid !== 'object') { return []; } let arrAllBids = []; let enhancedAdserverTargeting = config.getConfig('ozone.enhancedAdserverTargeting'); utils.logInfo('OZONE: enhancedAdserverTargeting', enhancedAdserverTargeting); if (typeof enhancedAdserverTargeting == 'undefined') { enhancedAdserverTargeting = true; } utils.logInfo('OZONE: enhancedAdserverTargeting', enhancedAdserverTargeting); serverResponse.seatbid = injectAdIdsIntoAllBidResponses(serverResponse.seatbid); // we now make sure that each bid in the bidresponse has a unique (within page) adId attribute. for (let i = 0; i < serverResponse.seatbid.length; i++) { let sb = serverResponse.seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { const {defaultWidth, defaultHeight} = defaultSize(request.bidderRequest.bids[j]); let thisBid = ozoneAddStandardProperties(sb.bid[j], defaultWidth, defaultHeight); // from https://github.com/prebid/Prebid.js/pull/1082 if (utils.deepAccess(thisBid, 'ext.prebid.type') === VIDEO) { utils.logInfo('OZONE: going to attach a renderer to:', j); let renderConf = createObjectForInternalVideoRender(thisBid); thisBid.renderer = Renderer.install(renderConf); } else { utils.logInfo('OZONE: bid is not a video, will not attach a renderer: ', j); } let ozoneInternalKey = thisBid.bidId; let adserverTargeting = {}; if (enhancedAdserverTargeting) { let allBidsForThisBidid = ozoneGetAllBidsForBidId(ozoneInternalKey, serverResponse.seatbid); // add all the winning & non-winning bids for this bidId: utils.logInfo('OZONE: Going to iterate allBidsForThisBidId', allBidsForThisBidid); Object.keys(allBidsForThisBidid).forEach(function (bidderName, index, ar2) { adserverTargeting['oz_' + bidderName] = bidderName; adserverTargeting['oz_' + bidderName + '_pb'] = String(allBidsForThisBidid[bidderName].price); adserverTargeting['oz_' + bidderName + '_crid'] = String(allBidsForThisBidid[bidderName].crid); adserverTargeting['oz_' + bidderName + '_adv'] = String(allBidsForThisBidid[bidderName].adomain); adserverTargeting['oz_' + bidderName + '_imp_id'] = String(allBidsForThisBidid[bidderName].impid); adserverTargeting['oz_' + bidderName + '_adId'] = String(allBidsForThisBidid[bidderName].adId); adserverTargeting['oz_' + bidderName + '_pb_r'] = getRoundedBid(allBidsForThisBidid[bidderName].price, allBidsForThisBidid[bidderName].ext.prebid.type); if (allBidsForThisBidid[bidderName].hasOwnProperty('dealid')) { adserverTargeting['oz_' + bidderName + '_dealid'] = String(allBidsForThisBidid[bidderName].dealid); } }); } // also add in the winning bid, to be sent to dfp let {seat: winningSeat, bid: winningBid} = ozoneGetWinnerForRequestBid(ozoneInternalKey, serverResponse.seatbid); adserverTargeting['oz_auc_id'] = String(request.bidderRequest.auctionId); adserverTargeting['oz_winner'] = String(winningSeat); adserverTargeting['oz_response_id'] = String(serverResponse.id); if (enhancedAdserverTargeting) { adserverTargeting['oz_winner_auc_id'] = String(winningBid.id); adserverTargeting['oz_winner_imp_id'] = String(winningBid.impid); adserverTargeting['oz_pb_v'] = OZONEVERSION; } thisBid.adserverTargeting = adserverTargeting; arrAllBids.push(thisBid); } } utils.logInfo('OZONE: interpretResponse going to return', arrAllBids); return arrAllBids; }
JavaScript
isLotameDataValid(lotameObj) { if (!lotameObj.hasOwnProperty('Profile')) return false; let prof = lotameObj.Profile; if (!prof.hasOwnProperty('tpid')) return false; if (!prof.hasOwnProperty('pid')) return false; let audiences = utils.deepAccess(prof, 'Audiences.Audience'); if (typeof audiences != 'object') { return false; } for (var i = 0; i < audiences.length; i++) { let aud = audiences[i]; if (!aud.hasOwnProperty('id')) { return false; } } return true; // All Audiences objects have an 'id' key }
isLotameDataValid(lotameObj) { if (!lotameObj.hasOwnProperty('Profile')) return false; let prof = lotameObj.Profile; if (!prof.hasOwnProperty('tpid')) return false; if (!prof.hasOwnProperty('pid')) return false; let audiences = utils.deepAccess(prof, 'Audiences.Audience'); if (typeof audiences != 'object') { return false; } for (var i = 0; i < audiences.length; i++) { let aud = audiences[i]; if (!aud.hasOwnProperty('id')) { return false; } } return true; // All Audiences objects have an 'id' key }
JavaScript
makeLotameObjectFromOverride(objOverride, lotameData) { if ((lotameData.hasOwnProperty('Profile') && Object.keys(lotameData.Profile).length < 3) || (!lotameData.hasOwnProperty('Profile'))) { // bad or empty lotame object (should contain pid, tpid & Audiences object) - build a total replacement utils.logInfo('makeLotameObjectFromOverride', 'will return a full default lotame object'); return { 'Profile': { 'tpid': objOverride['oz_lotametpid'], 'pid': objOverride['oz_lotamepid'], 'Audiences': {'Audience': [{'id': objOverride['oz_lotameid'], 'abbr': objOverride['oz_lotameid']}]} } }; } if (utils.deepAccess(lotameData, 'Profile.Audiences.Audience')) { utils.logInfo('makeLotameObjectFromOverride', 'will return the existing lotame object with updated Audience by oz_lotameid'); lotameData.Profile.Audiences.Audience = [{'id': objOverride['oz_lotameid'], 'abbr': objOverride['oz_lotameid']}]; return lotameData; } utils.logInfo('makeLotameObjectFromOverride', 'Weird error - failed to find Profile.Audiences.Audience in lotame object. Will return the object as-is'); return lotameData; }
makeLotameObjectFromOverride(objOverride, lotameData) { if ((lotameData.hasOwnProperty('Profile') && Object.keys(lotameData.Profile).length < 3) || (!lotameData.hasOwnProperty('Profile'))) { // bad or empty lotame object (should contain pid, tpid & Audiences object) - build a total replacement utils.logInfo('makeLotameObjectFromOverride', 'will return a full default lotame object'); return { 'Profile': { 'tpid': objOverride['oz_lotametpid'], 'pid': objOverride['oz_lotamepid'], 'Audiences': {'Audience': [{'id': objOverride['oz_lotameid'], 'abbr': objOverride['oz_lotameid']}]} } }; } if (utils.deepAccess(lotameData, 'Profile.Audiences.Audience')) { utils.logInfo('makeLotameObjectFromOverride', 'will return the existing lotame object with updated Audience by oz_lotameid'); lotameData.Profile.Audiences.Audience = [{'id': objOverride['oz_lotameid'], 'abbr': objOverride['oz_lotameid']}]; return lotameData; } utils.logInfo('makeLotameObjectFromOverride', 'Weird error - failed to find Profile.Audiences.Audience in lotame object. Will return the object as-is'); return lotameData; }
JavaScript
blockTheRequest(bidderRequest) { // if there is an ozone.oz_request = false then quit now. let ozRequest = config.getConfig('ozone.oz_request'); if (typeof ozRequest == 'boolean' && !ozRequest) { utils.logError('OZONE: Will not allow auction : ozone.oz_request is set to false'); return true; } // is there ozone.oz_enforceGdpr == true (ANYTHING else means don't enforce GDPR)) let ozEnforce = config.getConfig('ozone.oz_enforceGdpr'); if (typeof ozEnforce != 'boolean' || !ozEnforce) { // ozEnforce is false by default utils.logError('OZONE: Will not validate GDPR on the client : oz_enforceGdpr is not set to true'); return false; } // maybe the module was built without consentManagement module so we won't find any gdpr information if (!bidderRequest.hasOwnProperty('gdprConsent')) { return false; } // // FROM HERE ON : WE ARE DOING GDPR CHECKS // // If there is indeterminate GDPR (gdprConsent.consentString == undefined or not a string), we will DITCH this: if (typeof bidderRequest.gdprConsent.consentString !== 'string') { utils.logError('OZONE: Will block the request - bidderRequest.gdprConsent.consentString is not a string'); return true; } // IF the consentManagement module sends through the CMP information and user has refused all permissions: if (this.failsGdprCheck(bidderRequest)) { return true; } return false; }
blockTheRequest(bidderRequest) { // if there is an ozone.oz_request = false then quit now. let ozRequest = config.getConfig('ozone.oz_request'); if (typeof ozRequest == 'boolean' && !ozRequest) { utils.logError('OZONE: Will not allow auction : ozone.oz_request is set to false'); return true; } // is there ozone.oz_enforceGdpr == true (ANYTHING else means don't enforce GDPR)) let ozEnforce = config.getConfig('ozone.oz_enforceGdpr'); if (typeof ozEnforce != 'boolean' || !ozEnforce) { // ozEnforce is false by default utils.logError('OZONE: Will not validate GDPR on the client : oz_enforceGdpr is not set to true'); return false; } // maybe the module was built without consentManagement module so we won't find any gdpr information if (!bidderRequest.hasOwnProperty('gdprConsent')) { return false; } // // FROM HERE ON : WE ARE DOING GDPR CHECKS // // If there is indeterminate GDPR (gdprConsent.consentString == undefined or not a string), we will DITCH this: if (typeof bidderRequest.gdprConsent.consentString !== 'string') { utils.logError('OZONE: Will block the request - bidderRequest.gdprConsent.consentString is not a string'); return true; } // IF the consentManagement module sends through the CMP information and user has refused all permissions: if (this.failsGdprCheck(bidderRequest)) { return true; } return false; }
JavaScript
failsGdprCheck(bidderRequest) { let consentRequired = (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : true; if (consentRequired) { let vendorConsentsObject = utils.deepAccess(bidderRequest.gdprConsent, 'vendorData'); if (!vendorConsentsObject || typeof vendorConsentsObject !== 'object') { utils.logError('OZONE: gdpr test failed - bidderRequest.gdprConsent.vendorData is not an array'); return true; } if (!vendorConsentsObject.hasOwnProperty('purposeConsents')) { return true; } if (typeof vendorConsentsObject.purposeConsents != 'object') { return true; } if (!this.purposeConsentsAreOk((vendorConsentsObject.purposeConsents))) { utils.logError('OZONE: gdpr test failed - missing Purposes consent'); return true; } if (!vendorConsentsObject.vendorConsents[524]) { utils.logError('OZONE: gdpr test failed - missing Vendor ID consent'); return true; } } return false; }
failsGdprCheck(bidderRequest) { let consentRequired = (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : true; if (consentRequired) { let vendorConsentsObject = utils.deepAccess(bidderRequest.gdprConsent, 'vendorData'); if (!vendorConsentsObject || typeof vendorConsentsObject !== 'object') { utils.logError('OZONE: gdpr test failed - bidderRequest.gdprConsent.vendorData is not an array'); return true; } if (!vendorConsentsObject.hasOwnProperty('purposeConsents')) { return true; } if (typeof vendorConsentsObject.purposeConsents != 'object') { return true; } if (!this.purposeConsentsAreOk((vendorConsentsObject.purposeConsents))) { utils.logError('OZONE: gdpr test failed - missing Purposes consent'); return true; } if (!vendorConsentsObject.vendorConsents[524]) { utils.logError('OZONE: gdpr test failed - missing Vendor ID consent'); return true; } } return false; }
JavaScript
function injectAdIdsIntoAllBidResponses(seatbid) { utils.logInfo('injectAdIdsIntoAllBidResponses', seatbid); for (let i = 0; i < seatbid.length; i++) { let sb = seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { // modify the bidId per-bid, so each bid has a unique adId within this response, and dfp can select one. sb.bid[j]['adId'] = sb.bid[j]['impid'] + '-' + i; } } return seatbid; }
function injectAdIdsIntoAllBidResponses(seatbid) { utils.logInfo('injectAdIdsIntoAllBidResponses', seatbid); for (let i = 0; i < seatbid.length; i++) { let sb = seatbid[i]; for (let j = 0; j < sb.bid.length; j++) { // modify the bidId per-bid, so each bid has a unique adId within this response, and dfp can select one. sb.bid[j]['adId'] = sb.bid[j]['impid'] + '-' + i; } } return seatbid; }
JavaScript
function mockCmp(command, version, callback, parameter) { var resultVal; if (command == 'ping') { resultVal = { gdprAppliesGlobally: mockCmp.stubSettings.isGlobal }; callback(resultVal); } else if (command == 'getVendorConsents') { let cbResult = { vendorConsents: [] } cbResult.vendorConsents[version] = mockCmp.stubSettings.consents; callback(cbResult); } }
function mockCmp(command, version, callback, parameter) { var resultVal; if (command == 'ping') { resultVal = { gdprAppliesGlobally: mockCmp.stubSettings.isGlobal }; callback(resultVal); } else if (command == 'getVendorConsents') { let cbResult = { vendorConsents: [] } cbResult.vendorConsents[version] = mockCmp.stubSettings.consents; callback(cbResult); } }
JavaScript
function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; if (utils.isArray(requestSizes) && requestSizes.length === 2 && !utils.isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); } else if (typeof requestSizes === 'object') { for (let i = 0; i < requestSizes.length; i++) { let size = requestSizes[i]; sizeObj = {}; sizeObj.width = parseInt(size[0], 10); sizeObj.height = parseInt(size[1], 10); sizes.push(sizeObj); } } return sizes; }
function transformSizes(requestSizes) { let sizes = []; let sizeObj = {}; if (utils.isArray(requestSizes) && requestSizes.length === 2 && !utils.isArray(requestSizes[0])) { sizeObj.width = parseInt(requestSizes[0], 10); sizeObj.height = parseInt(requestSizes[1], 10); sizes.push(sizeObj); } else if (typeof requestSizes === 'object') { for (let i = 0; i < requestSizes.length; i++) { let size = requestSizes[i]; sizeObj = {}; sizeObj.width = parseInt(size[0], 10); sizeObj.height = parseInt(size[1], 10); sizes.push(sizeObj); } } return sizes; }
JavaScript
function checkAdUnitSetupHook(adUnits) { return adUnits.filter(adUnit => { const mediaTypes = adUnit.mediaTypes; if (!mediaTypes || Object.keys(mediaTypes).length === 0) { utils.logError(`Detected adUnit.code '${adUnit.code}' did not have a 'mediaTypes' object defined. This is a required field for the auction, so this adUnit has been removed.`); return false; } if (mediaTypes.banner) { const banner = mediaTypes.banner; if (banner.sizes) { adUnitSetupChecks.validateBannerMediaType(adUnit); } else if (banner.sizeConfig) { if (Array.isArray(banner.sizeConfig)) { let deleteBannerMediaType = false; banner.sizeConfig.forEach((config, index) => { // verify if all config objects include "minViewPort" and "sizes" property. // if not, remove the mediaTypes.banner object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'sizes'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] is missing required property minViewPort or sizes or both.`); deleteBannerMediaType = true; return; } // check if the config.sizes property is in [w, h] format, if yes, change it to [[w, h]] format. const bannerSizes = adUnitSetupChecks.validateSizes(config.sizes); if (utils.isArrayOfNums(config.minViewPort, 2)) { if (config.sizes.length > 0 && bannerSizes.length > 0) { config.sizes = bannerSizes; } else if (config.sizes.length === 0) { // If a size bucket doesn't have any sizes, sizes is an empty array, i.e. sizes: []. This check takes care of that. config.sizes = [config.sizes]; } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] has propery sizes declared with invalid value. Please ensure the sizes are listed like: [[300, 250], ...] or like: [] if no sizes are present for that size bucket.`); deleteBannerMediaType = true; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] has property minViewPort decalared with invalid value. Please ensure minViewPort is an Array and is listed like: [700, 0]. Declaring an empty array is not allowed, instead use: [0, 0].`); deleteBannerMediaType = true; } }); if (deleteBannerMediaType) { utils.logInfo(`Ad Unit: ${adUnit.code}: mediaTypes.banner has been removed due to error in sizeConfig.`); delete adUnit.mediaTypes.banner; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig is NOT an Array. Removing the invalid object mediaTypes.banner from Ad Unit.`); delete adUnit.mediaTypes.banner; } } else { utils.logError('Detected a mediaTypes.banner object did not include required property sizes or sizeConfig. Removing invalid mediaTypes.banner object from Ad Unit.'); delete adUnit.mediaTypes.banner; } } if (mediaTypes.video) { const video = mediaTypes.video; if (video.playerSize) { adUnitSetupChecks.validateVideoMediaType(adUnit); } else if (video.sizeConfig) { if (Array.isArray(video.sizeConfig)) { let deleteVideoMediaType = false; video.sizeConfig.forEach((config, index) => { // verify if all config objects include "minViewPort" and "playerSize" property. // if not, remove the mediaTypes.video object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'playerSize'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] is missing required property minViewPort or playerSize or both. Removing the invalid property mediaTypes.video.sizeConfig from Ad Unit.`); deleteVideoMediaType = true; return; } // check if the config.playerSize property is in [w, h] format, if yes, change it to [[w, h]] format. let tarPlayerSizeLen = (typeof config.playerSize[0] === 'number') ? 2 : 1; const videoSizes = adUnitSetupChecks.validateSizes(config.playerSize, tarPlayerSizeLen); if (utils.isArrayOfNums(config.minViewPort, 2)) { if (tarPlayerSizeLen === 2) { utils.logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.'); } if (config.playerSize.length > 0 && videoSizes.length > 0) { config.playerSize = videoSizes; } else if (config.playerSize.length === 0) { // If a size bucket doesn't have any playerSize, playerSize is an empty array, i.e. playerSize: []. This check takes care of that. config.playerSize = [config.playerSize]; } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] has propery playerSize declared with invalid value. Please ensure the playerSize is listed like: [640, 480] or like: [] if no playerSize is present for that size bucket.`); deleteVideoMediaType = true; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] has property minViewPort decalared with invalid value. Please ensure minViewPort is an Array and is listed like: [700, 0]. Declaring an empty array is not allowed, instead use: [0, 0].`); deleteVideoMediaType = true; } }); if (deleteVideoMediaType) { utils.logInfo(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig has been removed due to error in sizeConfig.`); delete adUnit.mediaTypes.video.sizeConfig; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig is NOT an Array. Removing the invalid property mediaTypes.video.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.video.sizeConfig; } } } if (mediaTypes.native) { const native = mediaTypes.native; adUnitSetupChecks.validateNativeMediaType(adUnit); if (mediaTypes.native.sizeConfig) { native.sizeConfig.forEach(config => { // verify if all config objects include "minViewPort" and "active" property. // if not, remove the mediaTypes.native object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'active'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.native.sizeConfig is missing required property minViewPort or active or both. Removing the invalid property mediaTypes.native.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.native.sizeConfig; } if (!(utils.isArrayOfNums(config.minViewPort, 2) && typeof config.active === 'boolean')) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.native.sizeConfig has properties minViewPort or active decalared with invalid values. Removing the invalid property mediaTypes.native.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.native.sizeConfig; } }); } } return true; }); }
function checkAdUnitSetupHook(adUnits) { return adUnits.filter(adUnit => { const mediaTypes = adUnit.mediaTypes; if (!mediaTypes || Object.keys(mediaTypes).length === 0) { utils.logError(`Detected adUnit.code '${adUnit.code}' did not have a 'mediaTypes' object defined. This is a required field for the auction, so this adUnit has been removed.`); return false; } if (mediaTypes.banner) { const banner = mediaTypes.banner; if (banner.sizes) { adUnitSetupChecks.validateBannerMediaType(adUnit); } else if (banner.sizeConfig) { if (Array.isArray(banner.sizeConfig)) { let deleteBannerMediaType = false; banner.sizeConfig.forEach((config, index) => { // verify if all config objects include "minViewPort" and "sizes" property. // if not, remove the mediaTypes.banner object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'sizes'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] is missing required property minViewPort or sizes or both.`); deleteBannerMediaType = true; return; } // check if the config.sizes property is in [w, h] format, if yes, change it to [[w, h]] format. const bannerSizes = adUnitSetupChecks.validateSizes(config.sizes); if (utils.isArrayOfNums(config.minViewPort, 2)) { if (config.sizes.length > 0 && bannerSizes.length > 0) { config.sizes = bannerSizes; } else if (config.sizes.length === 0) { // If a size bucket doesn't have any sizes, sizes is an empty array, i.e. sizes: []. This check takes care of that. config.sizes = [config.sizes]; } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] has propery sizes declared with invalid value. Please ensure the sizes are listed like: [[300, 250], ...] or like: [] if no sizes are present for that size bucket.`); deleteBannerMediaType = true; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig[${index}] has property minViewPort decalared with invalid value. Please ensure minViewPort is an Array and is listed like: [700, 0]. Declaring an empty array is not allowed, instead use: [0, 0].`); deleteBannerMediaType = true; } }); if (deleteBannerMediaType) { utils.logInfo(`Ad Unit: ${adUnit.code}: mediaTypes.banner has been removed due to error in sizeConfig.`); delete adUnit.mediaTypes.banner; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.banner.sizeConfig is NOT an Array. Removing the invalid object mediaTypes.banner from Ad Unit.`); delete adUnit.mediaTypes.banner; } } else { utils.logError('Detected a mediaTypes.banner object did not include required property sizes or sizeConfig. Removing invalid mediaTypes.banner object from Ad Unit.'); delete adUnit.mediaTypes.banner; } } if (mediaTypes.video) { const video = mediaTypes.video; if (video.playerSize) { adUnitSetupChecks.validateVideoMediaType(adUnit); } else if (video.sizeConfig) { if (Array.isArray(video.sizeConfig)) { let deleteVideoMediaType = false; video.sizeConfig.forEach((config, index) => { // verify if all config objects include "minViewPort" and "playerSize" property. // if not, remove the mediaTypes.video object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'playerSize'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] is missing required property minViewPort or playerSize or both. Removing the invalid property mediaTypes.video.sizeConfig from Ad Unit.`); deleteVideoMediaType = true; return; } // check if the config.playerSize property is in [w, h] format, if yes, change it to [[w, h]] format. let tarPlayerSizeLen = (typeof config.playerSize[0] === 'number') ? 2 : 1; const videoSizes = adUnitSetupChecks.validateSizes(config.playerSize, tarPlayerSizeLen); if (utils.isArrayOfNums(config.minViewPort, 2)) { if (tarPlayerSizeLen === 2) { utils.logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.'); } if (config.playerSize.length > 0 && videoSizes.length > 0) { config.playerSize = videoSizes; } else if (config.playerSize.length === 0) { // If a size bucket doesn't have any playerSize, playerSize is an empty array, i.e. playerSize: []. This check takes care of that. config.playerSize = [config.playerSize]; } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] has propery playerSize declared with invalid value. Please ensure the playerSize is listed like: [640, 480] or like: [] if no playerSize is present for that size bucket.`); deleteVideoMediaType = true; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig[${index}] has property minViewPort decalared with invalid value. Please ensure minViewPort is an Array and is listed like: [700, 0]. Declaring an empty array is not allowed, instead use: [0, 0].`); deleteVideoMediaType = true; } }); if (deleteVideoMediaType) { utils.logInfo(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig has been removed due to error in sizeConfig.`); delete adUnit.mediaTypes.video.sizeConfig; } } else { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.video.sizeConfig is NOT an Array. Removing the invalid property mediaTypes.video.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.video.sizeConfig; } } } if (mediaTypes.native) { const native = mediaTypes.native; adUnitSetupChecks.validateNativeMediaType(adUnit); if (mediaTypes.native.sizeConfig) { native.sizeConfig.forEach(config => { // verify if all config objects include "minViewPort" and "active" property. // if not, remove the mediaTypes.native object const keys = Object.keys(config); if (!(includes(keys, 'minViewPort') && includes(keys, 'active'))) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.native.sizeConfig is missing required property minViewPort or active or both. Removing the invalid property mediaTypes.native.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.native.sizeConfig; } if (!(utils.isArrayOfNums(config.minViewPort, 2) && typeof config.active === 'boolean')) { utils.logError(`Ad Unit: ${adUnit.code}: mediaTypes.native.sizeConfig has properties minViewPort or active decalared with invalid values. Removing the invalid property mediaTypes.native.sizeConfig from Ad Unit.`); return delete adUnit.mediaTypes.native.sizeConfig; } }); } } return true; }); }
JavaScript
function checkBidderSizeConfigFormat(sizeConfig) { let didCheckPass = true; if (Array.isArray(sizeConfig) && sizeConfig.length > 0) { sizeConfig.forEach(config => { const keys = Object.keys(config); if ((includes(keys, 'minViewPort') && includes(keys, 'relevantMediaTypes')) && utils.isArrayOfNums(config.minViewPort, 2) && Array.isArray(config.relevantMediaTypes) && config.relevantMediaTypes.length > 0 && (config.relevantMediaTypes.length > 1 ? (config.relevantMediaTypes.every(mt => (includes(['banner', 'video', 'native'], mt)))) : (['none', 'banner', 'video', 'native'].indexOf(config.relevantMediaTypes[0]) > -1))) { didCheckPass = didCheckPass && true; } else { didCheckPass = false; } }); } else { didCheckPass = false; } return didCheckPass; }
function checkBidderSizeConfigFormat(sizeConfig) { let didCheckPass = true; if (Array.isArray(sizeConfig) && sizeConfig.length > 0) { sizeConfig.forEach(config => { const keys = Object.keys(config); if ((includes(keys, 'minViewPort') && includes(keys, 'relevantMediaTypes')) && utils.isArrayOfNums(config.minViewPort, 2) && Array.isArray(config.relevantMediaTypes) && config.relevantMediaTypes.length > 0 && (config.relevantMediaTypes.length > 1 ? (config.relevantMediaTypes.every(mt => (includes(['banner', 'video', 'native'], mt)))) : (['none', 'banner', 'video', 'native'].indexOf(config.relevantMediaTypes[0]) > -1))) { didCheckPass = didCheckPass && true; } else { didCheckPass = false; } }); } else { didCheckPass = false; } return didCheckPass; }
JavaScript
function isLabelActivated(bidOrAdUnit, activeLabels, adUnitCode, adUnitInstance) { let labelOperator; const labelsFound = Object.keys(bidOrAdUnit).filter(prop => prop === 'labelAny' || prop === 'labelAll'); if (labelsFound && labelsFound.length > 1) { utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has multiple label operators. Using the first declared operator: ${labelsFound[0]}`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Bidder has multiple label operators. Using the first declared operator: ${labelsFound[0]}`)}`); } labelOperator = labelsFound[0]; if (labelOperator && !activeLabels) { utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Found '${labelOperator}' on ad unit, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Found '${labelOperator}' on bidder, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`)}`); return true; } if (labelOperator === 'labelAll' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAll.length === 0) { utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAll' with an empty array.`); return true; } return bidOrAdUnit.labelAll.every(label => includes(activeLabels, label)); } else if (labelOperator === 'labelAny' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAny.length === 0) { utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAny' with an empty array.`); return true; } return bidOrAdUnit.labelAny.some(label => includes(activeLabels, label)); } return true; }
function isLabelActivated(bidOrAdUnit, activeLabels, adUnitCode, adUnitInstance) { let labelOperator; const labelsFound = Object.keys(bidOrAdUnit).filter(prop => prop === 'labelAny' || prop === 'labelAll'); if (labelsFound && labelsFound.length > 1) { utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has multiple label operators. Using the first declared operator: ${labelsFound[0]}`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Bidder has multiple label operators. Using the first declared operator: ${labelsFound[0]}`)}`); } labelOperator = labelsFound[0]; if (labelOperator && !activeLabels) { utils.logWarn(`Size Mapping V2:: ${(bidOrAdUnit.code) ? (`Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Found '${labelOperator}' on ad unit, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`) : (`Ad Unit: ${adUnitCode}(${adUnitInstance}), Bidder: ${bidOrAdUnit.bidder} => Found '${labelOperator}' on bidder, but 'labels' is not set. Did you pass 'labels' to pbjs.requestBids() ?`)}`); return true; } if (labelOperator === 'labelAll' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAll.length === 0) { utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAll' with an empty array.`); return true; } return bidOrAdUnit.labelAll.every(label => includes(activeLabels, label)); } else if (labelOperator === 'labelAny' && Array.isArray(bidOrAdUnit[labelOperator])) { if (bidOrAdUnit.labelAny.length === 0) { utils.logWarn(`Size Mapping V2:: Ad Unit: ${bidOrAdUnit.code}(${adUnitInstance}) => Ad unit has declared property 'labelAny' with an empty array.`); return true; } return bidOrAdUnit.labelAny.some(label => includes(activeLabels, label)); } return true; }
JavaScript
function isSizeConfigActivated(mediaType, sizeConfig) { switch (mediaType) { case 'banner': // we need this check, sizeConfig.sizes[0].length > 0, in place because a sizeBucket can have sizes: [], // gets converted to sizes: [[]] in the checkAdUnitSetupHook function return sizeConfig.sizes && sizeConfig.sizes.length > 0 && sizeConfig.sizes[0].length > 0; case 'video': // for why we need the last check, read the above comment return sizeConfig.playerSize && sizeConfig.playerSize.length > 0 && sizeConfig.playerSize[0].length > 0; case 'native': return sizeConfig.active; default: return false; } }
function isSizeConfigActivated(mediaType, sizeConfig) { switch (mediaType) { case 'banner': // we need this check, sizeConfig.sizes[0].length > 0, in place because a sizeBucket can have sizes: [], // gets converted to sizes: [[]] in the checkAdUnitSetupHook function return sizeConfig.sizes && sizeConfig.sizes.length > 0 && sizeConfig.sizes[0].length > 0; case 'video': // for why we need the last check, read the above comment return sizeConfig.playerSize && sizeConfig.playerSize.length > 0 && sizeConfig.playerSize[0].length > 0; case 'native': return sizeConfig.active; default: return false; } }
JavaScript
function useVideoCacheStub(responses) { let storeStub; beforeEach(function () { storeStub = sinon.stub(videoCache, 'store'); if (responses.store instanceof Error) { storeStub.callsArgWith(1, responses.store); } else { storeStub.callsArgWith(1, null, responses.store); } }); afterEach(function () { videoCache.store.restore(); }); return function() { return { store: storeStub }; } }
function useVideoCacheStub(responses) { let storeStub; beforeEach(function () { storeStub = sinon.stub(videoCache, 'store'); if (responses.store instanceof Error) { storeStub.callsArgWith(1, responses.store); } else { storeStub.callsArgWith(1, null, responses.store); } }); afterEach(function () { videoCache.store.restore(); }); return function() { return { store: storeStub }; } }
JavaScript
function isDfp() { try { const frameElement = window.frameElement; const parentElement = window.frameElement.parentNode; if (frameElement && parentElement) { return ( frameElement.id.indexOf('google_ads_iframe') > -1 && parentElement.id.indexOf('google_ads_iframe') > -1 ); } return false; } catch (e) { return false; } }
function isDfp() { try { const frameElement = window.frameElement; const parentElement = window.frameElement.parentNode; if (frameElement && parentElement) { return ( frameElement.id.indexOf('google_ads_iframe') > -1 && parentElement.id.indexOf('google_ads_iframe') > -1 ); } return false; } catch (e) { return false; } }
JavaScript
function isAmp() { try { const ampContext = window.context || window.parent.context; if (ampContext && ampContext.pageViewId) { return ampContext; } return false; } catch (e) { return false; } }
function isAmp() { try { const ampContext = window.context || window.parent.context; if (ampContext && ampContext.pageViewId) { return ampContext; } return false; } catch (e) { return false; } }
JavaScript
function isDFPSafeFrame() { if (window.location && window.location.href) { const href = window.location.href; return ( isSafeFrame() && href.indexOf('google') !== -1 && href.indexOf('safeframe') !== -1 ); } return false; }
function isDFPSafeFrame() { if (window.location && window.location.href) { const href = window.location.href; return ( isSafeFrame() && href.indexOf('google') !== -1 && href.indexOf('safeframe') !== -1 ); } return false; }
JavaScript
function isSuperSandboxedIframe() { const sacrificialIframe = window.document.createElement('iframe'); try { sacrificialIframe.setAttribute('style', 'display:none'); window.document.body.appendChild(sacrificialIframe); sacrificialIframe.contentWindow._testVar = true; window.document.body.removeChild(sacrificialIframe); return false; } catch (e) { window.document.body.removeChild(sacrificialIframe); return true; } }
function isSuperSandboxedIframe() { const sacrificialIframe = window.document.createElement('iframe'); try { sacrificialIframe.setAttribute('style', 'display:none'); window.document.body.appendChild(sacrificialIframe); sacrificialIframe.contentWindow._testVar = true; window.document.body.removeChild(sacrificialIframe); return false; } catch (e) { window.document.body.removeChild(sacrificialIframe); return true; } }
JavaScript
function validateRules(rule, consentData, currentModule, gvlid) { // if vendor has exception => always true if (includes(rule.vendorExceptions || [], currentModule)) { return true; } // if enforcePurpose is false or purpose was granted isAllowed is true, otherwise false const purposeAllowed = rule.enforcePurpose === false || utils.deepAccess(consentData, 'vendorData.purpose.consents.1') === true; // if enforceVendor is false or vendor was granted isAllowed is true, otherwise false const vendorAllowed = rule.enforceVendor === false || utils.deepAccess(consentData, `vendorData.vendor.consents.${gvlid}`) === true; return purposeAllowed && vendorAllowed; }
function validateRules(rule, consentData, currentModule, gvlid) { // if vendor has exception => always true if (includes(rule.vendorExceptions || [], currentModule)) { return true; } // if enforcePurpose is false or purpose was granted isAllowed is true, otherwise false const purposeAllowed = rule.enforcePurpose === false || utils.deepAccess(consentData, 'vendorData.purpose.consents.1') === true; // if enforceVendor is false or vendor was granted isAllowed is true, otherwise false const vendorAllowed = rule.enforceVendor === false || utils.deepAccess(consentData, `vendorData.vendor.consents.${gvlid}`) === true; return purposeAllowed && vendorAllowed; }
JavaScript
function deviceAccessHook(fn, gvlid, moduleName, result) { result = Object.assign({}, { hasEnforcementHook: true }); if (!hasDeviceAccess()) { utils.logWarn('Device access is disabled by Publisher'); result.valid = false; fn.call(this, gvlid, moduleName, result); } else { const consentData = gdprDataHandler.getConsentData(); if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { if (!gvlid) { gvlid = getGvlid(); } const curModule = moduleName || config.getCurrentBidder(); const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, curModule, gvlid); if (isAllowed) { result.valid = true; fn.call(this, gvlid, moduleName, result); } else { utils.logWarn(`User denied Permission for Device access for ${curModule}`); result.valid = false; fn.call(this, gvlid, moduleName, result); } } else { utils.logInfo('Enforcing TCF2 only'); result.valid = true; fn.call(this, gvlid, moduleName, result); } } else { result.valid = true; fn.call(this, gvlid, moduleName, result); } } }
function deviceAccessHook(fn, gvlid, moduleName, result) { result = Object.assign({}, { hasEnforcementHook: true }); if (!hasDeviceAccess()) { utils.logWarn('Device access is disabled by Publisher'); result.valid = false; fn.call(this, gvlid, moduleName, result); } else { const consentData = gdprDataHandler.getConsentData(); if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { if (!gvlid) { gvlid = getGvlid(); } const curModule = moduleName || config.getCurrentBidder(); const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, curModule, gvlid); if (isAllowed) { result.valid = true; fn.call(this, gvlid, moduleName, result); } else { utils.logWarn(`User denied Permission for Device access for ${curModule}`); result.valid = false; fn.call(this, gvlid, moduleName, result); } } else { utils.logInfo('Enforcing TCF2 only'); result.valid = true; fn.call(this, gvlid, moduleName, result); } } else { result.valid = true; fn.call(this, gvlid, moduleName, result); } } }
JavaScript
function userSyncHook(fn, ...args) { const consentData = gdprDataHandler.getConsentData(); if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { const gvlid = getGvlid(); const curBidder = config.getCurrentBidder(); if (gvlid) { const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, curBidder, gvlid); if (isAllowed) { fn.call(this, ...args); } else { utils.logWarn(`User sync not allowed for ${curBidder}`); } } else { utils.logWarn(`User sync not allowed for ${curBidder}`); } } else { utils.logInfo('Enforcing TCF2 only'); fn.call(this, ...args); } } else { fn.call(this, ...args); } }
function userSyncHook(fn, ...args) { const consentData = gdprDataHandler.getConsentData(); if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { const gvlid = getGvlid(); const curBidder = config.getCurrentBidder(); if (gvlid) { const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, curBidder, gvlid); if (isAllowed) { fn.call(this, ...args); } else { utils.logWarn(`User sync not allowed for ${curBidder}`); } } else { utils.logWarn(`User sync not allowed for ${curBidder}`); } } else { utils.logInfo('Enforcing TCF2 only'); fn.call(this, ...args); } } else { fn.call(this, ...args); } }
JavaScript
function userIdHook(fn, submodules, consentData) { if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { let userIdModules = submodules.map((submodule) => { const gvlid = submodule.submodule.gvlid; const moduleName = submodule.submodule.name; if (gvlid) { const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, moduleName, gvlid); if (isAllowed) { return submodule; } else { utils.logWarn(`User denied permission to fetch user id for ${moduleName} User id module`); } } else { utils.logWarn(`User denied permission to fetch user id for ${moduleName} User id module`); } return undefined; }).filter(module => module) fn.call(this, userIdModules, {...consentData, hasValidated: true}); } else { utils.logInfo('Enforcing TCF2 only'); fn.call(this, submodules, consentData); } } else { fn.call(this, submodules, consentData); } }
function userIdHook(fn, submodules, consentData) { if (consentData && consentData.gdprApplies) { if (consentData.apiVersion === 2) { let userIdModules = submodules.map((submodule) => { const gvlid = submodule.submodule.gvlid; const moduleName = submodule.submodule.name; if (gvlid) { const purpose1Rule = find(enforcementRules, hasPurpose1); let isAllowed = validateRules(purpose1Rule, consentData, moduleName, gvlid); if (isAllowed) { return submodule; } else { utils.logWarn(`User denied permission to fetch user id for ${moduleName} User id module`); } } else { utils.logWarn(`User denied permission to fetch user id for ${moduleName} User id module`); } return undefined; }).filter(module => module) fn.call(this, userIdModules, {...consentData, hasValidated: true}); } else { utils.logInfo('Enforcing TCF2 only'); fn.call(this, submodules, consentData); } } else { fn.call(this, submodules, consentData); } }
JavaScript
function bidResponseAvailable(request, response) { const idToImpMap = {}; const idToBidMap = {}; const idToSlotConfig = {}; const bidResponse = response.body // extract the request bids and the response bids, keyed by impr-id const ortbRequest = request.data; ortbRequest.imp.forEach(imp => { idToImpMap[imp.id] = imp; }); if (bidResponse) { bidResponse.seatbid.forEach(seatBid => seatBid.bid.forEach(bid => { idToBidMap[bid.impid] = bid; })); } if (request.bidderRequest && request.bidderRequest.bids) { request.bidderRequest.bids.forEach(bid => { idToSlotConfig[bid.bidId] = bid; }); } const bids = []; Object.keys(idToImpMap).forEach(id => { if (idToBidMap[id]) { const bid = { requestId: id, cpm: idToBidMap[id].price, creative_id: idToBidMap[id].crid, creativeId: idToBidMap[id].crid, adId: id, ttl: idToBidMap[id].exp || DEFAULT_BID_TTL, netRevenue: DEFAULT_NET_REVENUE, currency: bidResponse.cur || DEFAULT_CURRENCY }; if (idToImpMap[id]['native']) { bid['native'] = nativeResponse(idToImpMap[id], idToBidMap[id]); bid.mediaType = 'native'; } else if (idToImpMap[id].video) { // for outstream, a renderer is specified if (idToSlotConfig[id] && utils.deepAccess(idToSlotConfig[id], 'mediaTypes.video.context') === 'outstream') { bid.renderer = outstreamRenderer(utils.deepAccess(idToSlotConfig[id], 'renderer.options'), utils.deepAccess(idToBidMap[id], 'ext.outstream')); } bid.vastXml = idToBidMap[id].adm; bid.mediaType = 'video'; bid.width = idToBidMap[id].w; bid.height = idToBidMap[id].h; } else { bid.ad = idToBidMap[id].adm; bid.width = idToBidMap[id].w || idToImpMap[id].banner.w; bid.height = idToBidMap[id].h || idToImpMap[id].banner.h; } bids.push(bid); } }); return bids; }
function bidResponseAvailable(request, response) { const idToImpMap = {}; const idToBidMap = {}; const idToSlotConfig = {}; const bidResponse = response.body // extract the request bids and the response bids, keyed by impr-id const ortbRequest = request.data; ortbRequest.imp.forEach(imp => { idToImpMap[imp.id] = imp; }); if (bidResponse) { bidResponse.seatbid.forEach(seatBid => seatBid.bid.forEach(bid => { idToBidMap[bid.impid] = bid; })); } if (request.bidderRequest && request.bidderRequest.bids) { request.bidderRequest.bids.forEach(bid => { idToSlotConfig[bid.bidId] = bid; }); } const bids = []; Object.keys(idToImpMap).forEach(id => { if (idToBidMap[id]) { const bid = { requestId: id, cpm: idToBidMap[id].price, creative_id: idToBidMap[id].crid, creativeId: idToBidMap[id].crid, adId: id, ttl: idToBidMap[id].exp || DEFAULT_BID_TTL, netRevenue: DEFAULT_NET_REVENUE, currency: bidResponse.cur || DEFAULT_CURRENCY }; if (idToImpMap[id]['native']) { bid['native'] = nativeResponse(idToImpMap[id], idToBidMap[id]); bid.mediaType = 'native'; } else if (idToImpMap[id].video) { // for outstream, a renderer is specified if (idToSlotConfig[id] && utils.deepAccess(idToSlotConfig[id], 'mediaTypes.video.context') === 'outstream') { bid.renderer = outstreamRenderer(utils.deepAccess(idToSlotConfig[id], 'renderer.options'), utils.deepAccess(idToBidMap[id], 'ext.outstream')); } bid.vastXml = idToBidMap[id].adm; bid.mediaType = 'video'; bid.width = idToBidMap[id].w; bid.height = idToBidMap[id].h; } else { bid.ad = idToBidMap[id].adm; bid.width = idToBidMap[id].w || idToImpMap[id].banner.w; bid.height = idToBidMap[id].h || idToImpMap[id].banner.h; } bids.push(bid); } }); return bids; }
JavaScript
function banner(slot) { const sizes = parseSizes(slot); const size = adSize(slot, sizes); return (slot.nativeParams || slot.params.video) ? null : { w: size[0], h: size[1], battr: slot.params.battr, format: sizes }; }
function banner(slot) { const sizes = parseSizes(slot); const size = adSize(slot, sizes); return (slot.nativeParams || slot.params.video) ? null : { w: size[0], h: size[1], battr: slot.params.battr, format: sizes }; }
JavaScript
function parseSizes(slot) { const sizes = utils.deepAccess(slot, 'mediaTypes.banner.sizes'); if (sizes && utils.isArray(sizes)) { return sizes.filter(sz => utils.isArray(sz) && sz.length === 2).map(sz => ({ w: sz[0], h: sz[1] })); } return null; }
function parseSizes(slot) { const sizes = utils.deepAccess(slot, 'mediaTypes.banner.sizes'); if (sizes && utils.isArray(sizes)) { return sizes.filter(sz => utils.isArray(sz) && sz.length === 2).map(sz => ({ w: sz[0], h: sz[1] })); } return null; }
JavaScript
function user(bidRequest, bidderRequest) { var ext = {}; if (bidderRequest) { if (bidderRequest.gdprConsent) { ext.consent = bidderRequest.gdprConsent.consentString; } } if (bidRequest) { if (bidRequest.userId) { ext.eids = []; addExternalUserId(ext.eids, bidRequest.userId.pubcid, 'pubcommon'); addExternalUserId(ext.eids, bidRequest.userId.britepoolid, 'britepool.com'); addExternalUserId(ext.eids, bidRequest.userId.criteoId, 'criteo'); addExternalUserId(ext.eids, bidRequest.userId.idl_env, 'identityLink'); addExternalUserId(ext.eids, bidRequest.userId.id5id, 'id5-sync.com'); addExternalUserId(ext.eids, bidRequest.userId.parrableid, 'parrable.com'); // liveintent if (bidRequest.userId.lipb && bidRequest.userId.lipb.lipbid) { addExternalUserId(ext.eids, bidRequest.userId.lipb.lipbid, 'liveintent.com'); } // TTD addExternalUserId(ext.eids, bidRequest.userId.tdid, 'adserver.org', { rtiPartner: 'TDID' }); // digitrust const digitrustResponse = bidRequest.userId.digitrustid; if (digitrustResponse && digitrustResponse.data) { var digitrust = {}; if (digitrustResponse.data.id) { digitrust.id = digitrustResponse.data.id; } if (digitrustResponse.data.keyv) { digitrust.keyv = digitrustResponse.data.keyv; } ext.digitrust = digitrust; } } } return { ext }; }
function user(bidRequest, bidderRequest) { var ext = {}; if (bidderRequest) { if (bidderRequest.gdprConsent) { ext.consent = bidderRequest.gdprConsent.consentString; } } if (bidRequest) { if (bidRequest.userId) { ext.eids = []; addExternalUserId(ext.eids, bidRequest.userId.pubcid, 'pubcommon'); addExternalUserId(ext.eids, bidRequest.userId.britepoolid, 'britepool.com'); addExternalUserId(ext.eids, bidRequest.userId.criteoId, 'criteo'); addExternalUserId(ext.eids, bidRequest.userId.idl_env, 'identityLink'); addExternalUserId(ext.eids, bidRequest.userId.id5id, 'id5-sync.com'); addExternalUserId(ext.eids, bidRequest.userId.parrableid, 'parrable.com'); // liveintent if (bidRequest.userId.lipb && bidRequest.userId.lipb.lipbid) { addExternalUserId(ext.eids, bidRequest.userId.lipb.lipbid, 'liveintent.com'); } // TTD addExternalUserId(ext.eids, bidRequest.userId.tdid, 'adserver.org', { rtiPartner: 'TDID' }); // digitrust const digitrustResponse = bidRequest.userId.digitrustid; if (digitrustResponse && digitrustResponse.data) { var digitrust = {}; if (digitrustResponse.data.id) { digitrust.id = digitrustResponse.data.id; } if (digitrustResponse.data.keyv) { digitrust.keyv = digitrustResponse.data.keyv; } ext.digitrust = digitrust; } } } return { ext }; }
JavaScript
function _getFeatures(bidRequest) { if (!canAccessTopWindow()) return; const w = utils.getWindowTop(); const adUnitCode = bidRequest.adUnitCode; const adUnitElementId = bidRequest.params.adUnitElementId || _autoDetectAdUnitElementId(adUnitCode); let element; if (!adUnitElementId) { utils.logWarn('Unable to detect adUnitElementId. Adagio measures won\'t start'); } else { if (bidRequest.params.postBid === true) { window.document.getElementById(adUnitElementId); element = _getElementFromTopWindow(element, window); w.ADAGIO.pbjsAdUnits.map((adUnit) => { if (adUnit.code === adUnitCode) { const outerElementId = element.getAttribute('id'); adUnit.outerAdUnitElementId = outerElementId; bidRequest.params.outerAdUnitElementId = outerElementId; } }); } else { element = w.document.getElementById(adUnitElementId); } } const features = { print_number: _features.getPrintNumber(bidRequest.adUnitCode).toString(), page_dimensions: _features.getPageDimensions().toString(), viewport_dimensions: _features.getViewPortDimensions().toString(), dom_loading: _features.isDomLoading().toString(), // layout: features.getLayout().toString(), adunit_position: _features.getSlotPosition(element).toString(), user_timestamp: _features.getTimestamp().toString(), device: _features.getDevice().toString(), url: w.location.origin + w.location.pathname, browser: _features.getBrowser(), os: _features.getOS() }; const adUnitFeature = {}; adUnitFeature[adUnitElementId] = { features: features, version: FEATURES_VERSION }; _pushInAdagioQueue({ action: 'features', ts: Date.now(), data: adUnitFeature }); return features; }
function _getFeatures(bidRequest) { if (!canAccessTopWindow()) return; const w = utils.getWindowTop(); const adUnitCode = bidRequest.adUnitCode; const adUnitElementId = bidRequest.params.adUnitElementId || _autoDetectAdUnitElementId(adUnitCode); let element; if (!adUnitElementId) { utils.logWarn('Unable to detect adUnitElementId. Adagio measures won\'t start'); } else { if (bidRequest.params.postBid === true) { window.document.getElementById(adUnitElementId); element = _getElementFromTopWindow(element, window); w.ADAGIO.pbjsAdUnits.map((adUnit) => { if (adUnit.code === adUnitCode) { const outerElementId = element.getAttribute('id'); adUnit.outerAdUnitElementId = outerElementId; bidRequest.params.outerAdUnitElementId = outerElementId; } }); } else { element = w.document.getElementById(adUnitElementId); } } const features = { print_number: _features.getPrintNumber(bidRequest.adUnitCode).toString(), page_dimensions: _features.getPageDimensions().toString(), viewport_dimensions: _features.getViewPortDimensions().toString(), dom_loading: _features.isDomLoading().toString(), // layout: features.getLayout().toString(), adunit_position: _features.getSlotPosition(element).toString(), user_timestamp: _features.getTimestamp().toString(), device: _features.getDevice().toString(), url: w.location.origin + w.location.pathname, browser: _features.getBrowser(), os: _features.getOS() }; const adUnitFeature = {}; adUnitFeature[adUnitElementId] = { features: features, version: FEATURES_VERSION }; _pushInAdagioQueue({ action: 'features', ts: Date.now(), data: adUnitFeature }); return features; }
JavaScript
function extractTopWindowUrlFromBidRequest(bidRequest) { if (bidRequest && utils.deepAccess(bidRequest, 'refererInfo.canonicalUrl')) { return bidRequest.refererInfo.canonicalUrl; } try { return window.top.location.href; } catch (e) { return window.location.href; } }
function extractTopWindowUrlFromBidRequest(bidRequest) { if (bidRequest && utils.deepAccess(bidRequest, 'refererInfo.canonicalUrl')) { return bidRequest.refererInfo.canonicalUrl; } try { return window.top.location.href; } catch (e) { return window.location.href; } }
JavaScript
function extractTopWindowReferrerFromBidRequest(bidRequest) { if (bidRequest && utils.deepAccess(bidRequest, 'refererInfo.referer')) { return bidRequest.refererInfo.referer; } try { return window.top.document.referrer; } catch (e) { return window.document.referrer; } }
function extractTopWindowReferrerFromBidRequest(bidRequest) { if (bidRequest && utils.deepAccess(bidRequest, 'refererInfo.referer')) { return bidRequest.refererInfo.referer; } try { return window.top.document.referrer; } catch (e) { return window.document.referrer; } }
JavaScript
isBidRequestValid(bid) { return ( !!bid.params.placeId && !!bid.params.placement && ( (getMediaTypeFromBid(bid) === BANNER && bid.params.placement === 'banner') || (getMediaTypeFromBid(bid) === VIDEO && bid.params.placement === 'video' && hasVideoMandatoryParams(bid.mediaTypes)) ) ); }
isBidRequestValid(bid) { return ( !!bid.params.placeId && !!bid.params.placement && ( (getMediaTypeFromBid(bid) === BANNER && bid.params.placement === 'banner') || (getMediaTypeFromBid(bid) === VIDEO && bid.params.placement === 'video' && hasVideoMandatoryParams(bid.mediaTypes)) ) ); }
JavaScript
buildRequests(validBidRequests, bidderRequest) { const payload = { url: bidderRequest.refererInfo.referer, cmp: !!bidderRequest.gdprConsent, trafficType: TRAFFIC_TYPE_WEB, bidRequests: buildBidRequests(validBidRequests) }; if (payload.cmp) { const gdprApplies = bidderRequest.gdprConsent.gdprApplies; if (gdprApplies !== undefined) payload['ga'] = gdprApplies; payload['cs'] = bidderRequest.gdprConsent.consentString; } const payloadString = JSON.stringify(payload); return { method: 'POST', url: DSP_ENDPOINT, data: payloadString, options: { contentType: 'application/json' } } }
buildRequests(validBidRequests, bidderRequest) { const payload = { url: bidderRequest.refererInfo.referer, cmp: !!bidderRequest.gdprConsent, trafficType: TRAFFIC_TYPE_WEB, bidRequests: buildBidRequests(validBidRequests) }; if (payload.cmp) { const gdprApplies = bidderRequest.gdprConsent.gdprApplies; if (gdprApplies !== undefined) payload['ga'] = gdprApplies; payload['cs'] = bidderRequest.gdprConsent.consentString; } const payloadString = JSON.stringify(payload); return { method: 'POST', url: DSP_ENDPOINT, data: payloadString, options: { contentType: 'application/json' } } }
JavaScript
isBidRequestValid(bid) { return getMediaTypeFromBid(bid) === VIDEO ? hasMandatoryParams(bid.params) && hasVideoMandatoryParams(bid.mediaTypes) : hasMandatoryParams(bid.params); }
isBidRequestValid(bid) { return getMediaTypeFromBid(bid) === VIDEO ? hasMandatoryParams(bid.params) && hasVideoMandatoryParams(bid.mediaTypes) : hasMandatoryParams(bid.params); }
JavaScript
buildRequests(validBidRequests, bidderRequest) { const payload = { url: bidderRequest.refererInfo.referer, publisherToken: validBidRequests[0].params.publisherId, cmp: !!bidderRequest.gdprConsent, timeout: bidderRequest.timeout, version: '$prebid.version$', bidRequests: buildBidRequests(validBidRequests) }; if (payload.cmp) { const gdprApplies = bidderRequest.gdprConsent.gdprApplies; if (gdprApplies !== undefined) payload['ga'] = gdprApplies; payload['cd'] = bidderRequest.gdprConsent.consentString; } const payloadString = JSON.stringify(payload) return { method: 'POST', url: SEEDTAG_SSP_ENDPOINT, data: payloadString } }
buildRequests(validBidRequests, bidderRequest) { const payload = { url: bidderRequest.refererInfo.referer, publisherToken: validBidRequests[0].params.publisherId, cmp: !!bidderRequest.gdprConsent, timeout: bidderRequest.timeout, version: '$prebid.version$', bidRequests: buildBidRequests(validBidRequests) }; if (payload.cmp) { const gdprApplies = bidderRequest.gdprConsent.gdprApplies; if (gdprApplies !== undefined) payload['ga'] = gdprApplies; payload['cd'] = bidderRequest.gdprConsent.consentString; } const payloadString = JSON.stringify(payload) return { method: 'POST', url: SEEDTAG_SSP_ENDPOINT, data: payloadString } }
JavaScript
function createPrebidNativeAd(payload) { return { title: payload.products[0].title, body: payload.products[0].description, sponsoredBy: payload.advertiser.description, icon: payload.advertiser.logo, image: payload.products[0].image, clickUrl: payload.products[0].click_url, privacyLink: payload.privacy.optout_click_url, privacyIcon: payload.privacy.optout_image_url, cta: payload.products[0].call_to_action, price: payload.products[0].price, impressionTrackers: payload.impression_pixels.map(pix => pix.url) }; }
function createPrebidNativeAd(payload) { return { title: payload.products[0].title, body: payload.products[0].description, sponsoredBy: payload.advertiser.description, icon: payload.advertiser.logo, image: payload.products[0].image, clickUrl: payload.products[0].click_url, privacyLink: payload.privacy.optout_click_url, privacyIcon: payload.privacy.optout_image_url, cta: payload.products[0].call_to_action, price: payload.products[0].price, impressionTrackers: payload.impression_pixels.map(pix => pix.url) }; }
JavaScript
function populateCards(comments) { var $cards = $cardList.html(''); comments.forEach(function(comment) { new Card({ text: comment.text, module: comment.module, indices: comment.indices}).appendTo($cards); }); }
function populateCards(comments) { var $cards = $cardList.html(''); comments.forEach(function(comment) { new Card({ text: comment.text, module: comment.module, indices: comment.indices}).appendTo($cards); }); }
JavaScript
function showCards(show) { var elements = { '#no_comments': show, '#yes_comments': !show, '#cards': !show, }; Object.keys(elements).forEach(function(key) { $(key)[elements[key] ? 'addClass' : 'removeClass']('hidden'); }); }
function showCards(show) { var elements = { '#no_comments': show, '#yes_comments': !show, '#cards': !show, }; Object.keys(elements).forEach(function(key) { $(key)[elements[key] ? 'addClass' : 'removeClass']('hidden'); }); }
JavaScript
function analysisStart(location) { toggleSpinner(true); // Poll the server for the comments var id = setInterval(function() { Ajax.checkStatus(location, function(response) { // If no response, continue if (!response) {return;} // Otherwise, stop polling clearInterval(id); // Extract the comments comments = response.comments; // Hide the spinner toggleSpinner(false); // Populate and render the cards populateCards(comments); showCards(true); // Initially all cards are selected selectAllCards(); toggleUnhighlightAllButton(true); listenOnCards(); }); }, CHECK_STATUS_DELAY); }
function analysisStart(location) { toggleSpinner(true); // Poll the server for the comments var id = setInterval(function() { Ajax.checkStatus(location, function(response) { // If no response, continue if (!response) {return;} // Otherwise, stop polling clearInterval(id); // Extract the comments comments = response.comments; // Hide the spinner toggleSpinner(false); // Populate and render the cards populateCards(comments); showCards(true); // Initially all cards are selected selectAllCards(); toggleUnhighlightAllButton(true); listenOnCards(); }); }, CHECK_STATUS_DELAY); }
JavaScript
function Results({ children }) { return ( <div className="results-overflow-container"> <ul className="results-group">{children}</ul> </div> ); }
function Results({ children }) { return ( <div className="results-overflow-container"> <ul className="results-group">{children}</ul> </div> ); }
JavaScript
function ajouterUnMois(stringDate){ let date = new Date(stringDate); let mois = date.getMonth(); date.setMonth(mois+1); return formaterLaDate(date); }
function ajouterUnMois(stringDate){ let date = new Date(stringDate); let mois = date.getMonth(); date.setMonth(mois+1); return formaterLaDate(date); }
JavaScript
function utiliserDom(){ /* * getElementsByTagName retourne un tableau des noeuds. * https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName */ // Un seule élément body. let parent = document.getElementsByTagName("body").item(0); console.log(parent.tagName); //Plusieurs éléments p. let paragraphes = document.getElementsByTagName("p"); console.log(paragraphes.length); let dernierP = paragraphes.item(paragraphes.length-2); console.log(dernierP.innerHTML); /* * getElementById ne peut retourner qu'un élément. Id est unique. * https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById */ let form = document.getElementById("f1"); console.log("Form.name: "+form.name); /* * Ajout d'un élément dans la structure */ let nouveauInput = document.createElement("input"); nouveauInput.setAttribute("type","text"); console.log(nouveauInput.name); nouveauInput.setAttribute("name","t2"); console.log(nouveauInput.name); form.appendChild(nouveauInput); let nouveauParagraphe = document.createElement("p"); let texte = document.createTextNode("Nouveau paragraphe"); nouveauParagraphe.appendChild(texte); /*** * Le noeud est une élément unique. S'il est réaffecté commen enfant * d'un parent différent, il est déplacé dans l'IPM (GUI). */ parent.appendChild(nouveauParagraphe); parent.insertBefore(nouveauParagraphe,form); parent.appendChild(nouveauParagraphe); /* * Le noeud parent est utilisable avec parentNode. * https://developer.mozilla.org/fr/docs/Web/API/Node/parentNode */ let noeud1 = document.getElementById("t1"); console.log("Noeud parent: "+noeud1.parentNode.name); }
function utiliserDom(){ /* * getElementsByTagName retourne un tableau des noeuds. * https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName */ // Un seule élément body. let parent = document.getElementsByTagName("body").item(0); console.log(parent.tagName); //Plusieurs éléments p. let paragraphes = document.getElementsByTagName("p"); console.log(paragraphes.length); let dernierP = paragraphes.item(paragraphes.length-2); console.log(dernierP.innerHTML); /* * getElementById ne peut retourner qu'un élément. Id est unique. * https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById */ let form = document.getElementById("f1"); console.log("Form.name: "+form.name); /* * Ajout d'un élément dans la structure */ let nouveauInput = document.createElement("input"); nouveauInput.setAttribute("type","text"); console.log(nouveauInput.name); nouveauInput.setAttribute("name","t2"); console.log(nouveauInput.name); form.appendChild(nouveauInput); let nouveauParagraphe = document.createElement("p"); let texte = document.createTextNode("Nouveau paragraphe"); nouveauParagraphe.appendChild(texte); /*** * Le noeud est une élément unique. S'il est réaffecté commen enfant * d'un parent différent, il est déplacé dans l'IPM (GUI). */ parent.appendChild(nouveauParagraphe); parent.insertBefore(nouveauParagraphe,form); parent.appendChild(nouveauParagraphe); /* * Le noeud parent est utilisable avec parentNode. * https://developer.mozilla.org/fr/docs/Web/API/Node/parentNode */ let noeud1 = document.getElementById("t1"); console.log("Noeud parent: "+noeud1.parentNode.name); }
JavaScript
async function takeScreenshot(screenshotRectangle) { // Temporarily hide the rectangle element (so it's not included in the image) screenshotRectangle.style.opacity = 0; const canvas = await html2canvas(document.body, { // Library misses x axis by ~8px so it is necessary to add it manually allowTaint: true, x: screenshotRectangle.getBoundingClientRect().x + 8, y: screenshotRectangle.getBoundingClientRect().y, scrollY: document.body.getBoundingClientRect().y, width: screenshotRectangle.clientWidth, height: screenshotRectangle.clientHeight, useCORS: true }); const imageUrl = canvas.toDataURL('image/png'); screenshotRectangle.style.opacity = 1; return imageUrl; }
async function takeScreenshot(screenshotRectangle) { // Temporarily hide the rectangle element (so it's not included in the image) screenshotRectangle.style.opacity = 0; const canvas = await html2canvas(document.body, { // Library misses x axis by ~8px so it is necessary to add it manually allowTaint: true, x: screenshotRectangle.getBoundingClientRect().x + 8, y: screenshotRectangle.getBoundingClientRect().y, scrollY: document.body.getBoundingClientRect().y, width: screenshotRectangle.clientWidth, height: screenshotRectangle.clientHeight, useCORS: true }); const imageUrl = canvas.toDataURL('image/png'); screenshotRectangle.style.opacity = 1; return imageUrl; }
JavaScript
function binaryToArrayBuffer(binary) { const length = binary.length; let buffer = new ArrayBuffer(length); let arr = new Uint8Array(buffer); for (let i = 0; i < length; i++) { arr[i] = binary.charCodeAt(i); } return buffer; }
function binaryToArrayBuffer(binary) { const length = binary.length; let buffer = new ArrayBuffer(length); let arr = new Uint8Array(buffer); for (let i = 0; i < length; i++) { arr[i] = binary.charCodeAt(i); } return buffer; }
JavaScript
async function attachImageToClipboard(imageDataUrl) { const base64InBinary = atob(imageDataUrl.split('base64,')[1]); const arrayBuffer = binaryToArrayBuffer(base64InBinary); const imageBlob = new Blob([arrayBuffer], { type: 'image/png' }); await navigator.clipboard.write([ new ClipboardItem({ 'image/png': imageBlob }) ]); return imageBlob; }
async function attachImageToClipboard(imageDataUrl) { const base64InBinary = atob(imageDataUrl.split('base64,')[1]); const arrayBuffer = binaryToArrayBuffer(base64InBinary); const imageBlob = new Blob([arrayBuffer], { type: 'image/png' }); await navigator.clipboard.write([ new ClipboardItem({ 'image/png': imageBlob }) ]); return imageBlob; }
JavaScript
async function postTweet(pageLink, imageUrl) { // Attach image to clipboard and read it await attachImageToClipboard(imageUrl); await navigator.clipboard.read(); window.open(`https://twitter.com/compose/tweet?text=${pageLink}`); // Wait for page to load, ~2500ms setTimeout(() => { chrome.runtime.sendMessage({}, response => {}); }, 2500); }
async function postTweet(pageLink, imageUrl) { // Attach image to clipboard and read it await attachImageToClipboard(imageUrl); await navigator.clipboard.read(); window.open(`https://twitter.com/compose/tweet?text=${pageLink}`); // Wait for page to load, ~2500ms setTimeout(() => { chrome.runtime.sendMessage({}, response => {}); }, 2500); }
JavaScript
function removeElement(element) { try { element.remove(); return element; } catch (error) { // Element doesn't exist, no action needed return null; } }
function removeElement(element) { try { element.remove(); return element; } catch (error) { // Element doesn't exist, no action needed return null; } }
JavaScript
function dragMoveListener(event) { var target = event.target; // keep the dragged position in the data-x/data-y attributes var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx; var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; // translate the element target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'; // update the position attributes target.setAttribute('data-x', x); target.setAttribute('data-y', y); }
function dragMoveListener(event) { var target = event.target; // keep the dragged position in the data-x/data-y attributes var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx; var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; // translate the element target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'; // update the position attributes target.setAttribute('data-x', x); target.setAttribute('data-y', y); }
JavaScript
function initCorners(element) { const cornerIDs = [ 'corner-top-left', 'corner-top-right', 'corner-bottom-left', 'corner-bottom-right' ]; // Attach 4 corners with their respective IDs for (const cornerId of cornerIDs) { const corner = document.createElement('div'); corner.id = cornerId; element.appendChild(corner); } }
function initCorners(element) { const cornerIDs = [ 'corner-top-left', 'corner-top-right', 'corner-bottom-left', 'corner-bottom-right' ]; // Attach 4 corners with their respective IDs for (const cornerId of cornerIDs) { const corner = document.createElement('div'); corner.id = cornerId; element.appendChild(corner); } }
JavaScript
function initUsageMessage(element) { const messageEl = document.createElement('div'); messageEl.id = 'screenshot-rectangle-message'; messageEl.textContent = 'Press "Enter" to Tweet!'; element.appendChild(messageEl); }
function initUsageMessage(element) { const messageEl = document.createElement('div'); messageEl.id = 'screenshot-rectangle-message'; messageEl.textContent = 'Press "Enter" to Tweet!'; element.appendChild(messageEl); }
JavaScript
function removeUsageMessage() { const usageMessageEl = document.querySelector( '#screenshot-rectangle-message' ); if (usageMessageEl) { usageMessageEl.remove(); } return usageMessageEl; }
function removeUsageMessage() { const usageMessageEl = document.querySelector( '#screenshot-rectangle-message' ); if (usageMessageEl) { usageMessageEl.remove(); } return usageMessageEl; }
JavaScript
function analyzeTypeIntrospection(type) { let isRequired = false let itemsRequired = false let isArray = false // eslint-disable-next-line no-constant-condition while (true) { if (type.kind === KINDS.NON_NULL) { // If we already know this is an array, then this NonNull means that the // "items" are required if (isArray) { itemsRequired = true } else { // Otherwise, we are just saying that the outer thing (which may // not be an array) is required isRequired = true } } else if (type.kind === KINDS.LIST) { isArray = true } else { break } type = type.ofType } return { underlyingType: type, isRequired, isArray, itemsRequired, } }
function analyzeTypeIntrospection(type) { let isRequired = false let itemsRequired = false let isArray = false // eslint-disable-next-line no-constant-condition while (true) { if (type.kind === KINDS.NON_NULL) { // If we already know this is an array, then this NonNull means that the // "items" are required if (isArray) { itemsRequired = true } else { // Otherwise, we are just saying that the outer thing (which may // not be an array) is required isRequired = true } } else if (type.kind === KINDS.LIST) { isArray = true } else { break } type = type.ofType } return { underlyingType: type, isRequired, isArray, itemsRequired, } }
JavaScript
function ourFunction(hljs) { const VARIABLES = { className: 'code', begin: '\\$', end: '\\w+', excludeEnd: false, } const TYPES = { className: 'type', begin: '[^\\w][A-Z][a-z]', end: '[!\\W]', excludeEnd: false, } const FRAGMENT = { className: 'type', begin: /\.\.\./, end: /Fragment\b/, excludeEnd: false, } const ARGS = { className: 'tag', begin: /\(/, end: /\)/, excludeBegin: false, excludeEnd: false, contains: [TYPES, hljs.NUMBER_MODE, VARIABLES], } const LITERALS = { keyword: 'query mutation subscription|10 input schema directive interface union scalar fragment|10 enum on ...', literal: 'true false null', } const FIELD = { className: 'symbol', begin: /\w/, end: /\n/, keywords: LITERALS, excludeEnd: true, } const QUERY = { className: 'tag', begin: /{/, end: /}/, contains: [FIELD, FRAGMENT], excludeBegin: false, excludeEnd: false, relevance: 0, illegal: '\\S', } FIELD.contains = [ARGS, QUERY] return { aliases: ['gql'], keywords: LITERALS, contains: [QUERY, FIELD], illegal: /([;<']|BEGIN)/, } }
function ourFunction(hljs) { const VARIABLES = { className: 'code', begin: '\\$', end: '\\w+', excludeEnd: false, } const TYPES = { className: 'type', begin: '[^\\w][A-Z][a-z]', end: '[!\\W]', excludeEnd: false, } const FRAGMENT = { className: 'type', begin: /\.\.\./, end: /Fragment\b/, excludeEnd: false, } const ARGS = { className: 'tag', begin: /\(/, end: /\)/, excludeBegin: false, excludeEnd: false, contains: [TYPES, hljs.NUMBER_MODE, VARIABLES], } const LITERALS = { keyword: 'query mutation subscription|10 input schema directive interface union scalar fragment|10 enum on ...', literal: 'true false null', } const FIELD = { className: 'symbol', begin: /\w/, end: /\n/, keywords: LITERALS, excludeEnd: true, } const QUERY = { className: 'tag', begin: /{/, end: /}/, contains: [FIELD, FRAGMENT], excludeBegin: false, excludeEnd: false, relevance: 0, illegal: '\\S', } FIELD.contains = [ARGS, QUERY] return { aliases: ['gql'], keywords: LITERALS, contains: [QUERY, FIELD], illegal: /([;<']|BEGIN)/, } }
JavaScript
function hljsFunction(hljs) { const regex = hljs.regex const GQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/ return { name: 'GraphQL', aliases: ['gql'], case_insensitive: true, disableAutodetect: false, keywords: { keyword: [ 'query', 'mutation', 'subscription', 'type', 'input', 'schema', 'directive', 'interface', 'union', 'scalar', 'fragment', 'enum', 'on', ], literal: ['true', 'false', 'null'], }, contains: [ hljs.HASH_COMMENT_MODE, hljs.QUOTE_STRING_MODE, hljs.NUMBER_MODE, { scope: 'punctuation', match: /[.]{3}/, relevance: 0, }, { scope: 'punctuation', begin: /[!():=[\]{|}]{1}/, relevance: 0, }, { scope: 'variable', begin: /\$/, end: /\W/, excludeEnd: true, relevance: 0, }, { scope: 'meta', match: /@\w+/, excludeEnd: true, }, { scope: 'symbol', begin: regex.concat(GQL_NAME, regex.lookahead(/\s*:/)), relevance: 0, }, ], illegal: [/[;<']/, /BEGIN/], } }
function hljsFunction(hljs) { const regex = hljs.regex const GQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/ return { name: 'GraphQL', aliases: ['gql'], case_insensitive: true, disableAutodetect: false, keywords: { keyword: [ 'query', 'mutation', 'subscription', 'type', 'input', 'schema', 'directive', 'interface', 'union', 'scalar', 'fragment', 'enum', 'on', ], literal: ['true', 'false', 'null'], }, contains: [ hljs.HASH_COMMENT_MODE, hljs.QUOTE_STRING_MODE, hljs.NUMBER_MODE, { scope: 'punctuation', match: /[.]{3}/, relevance: 0, }, { scope: 'punctuation', begin: /[!():=[\]{|}]{1}/, relevance: 0, }, { scope: 'variable', begin: /\$/, end: /\W/, excludeEnd: true, relevance: 0, }, { scope: 'meta', match: /@\w+/, excludeEnd: true, }, { scope: 'symbol', begin: regex.concat(GQL_NAME, regex.lookahead(/\s*:/)), relevance: 0, }, ], illegal: [/[;<']/, /BEGIN/], } }
JavaScript
calcTime(){ // number of ingredients const numIng = this.ingredients.length; // number of 15 minute periods that we have const periods = Math.ceil(numIng / 3); this.time = periods * 15; }
calcTime(){ // number of ingredients const numIng = this.ingredients.length; // number of 15 minute periods that we have const periods = Math.ceil(numIng / 3); this.time = periods * 15; }
JavaScript
parseIngredients(){ // need to put words with S first, so that it doesnt partially replace our unitsLong words const unitsLong = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds']; const unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound']; //starts our array with the items inside of unitsShort const units = [...unitsShort, 'kg', 'g'] // function that changes our strings to seperate const newIngredients = this.ingredients.map(el => { // uniform units of measurements let ingredient = el.toLowerCase(); // if we find any of the unitsLong words, we replace it with the same positioned unitsShort abbreviation unitsLong.forEach((unit, i) => { ingredient = ingredient.replace(unit, unitsShort[i]); }); // remove parentheses with regular expression, we replace parentheses with a space ingredient = ingredient.replace(/ *\([^)]*\) */g, " "); // parse ingredients into count, unit and ingredient const arrIng = ingredient.split(' '); // find the index, where the unit is located, indexOf() doesnt work here b/c we dont know what unit were looking for // includes - returns true if the element were passing is in the units array const unitIndex = arrIng.findIndex(el2 => units.includes(el2)); // if there is an unit let objIng; if(unitIndex > -1){ // array ingredients, sliced from the beginning until the unitIndex excluding //example: 4 1/2 cups = arrCount is [4,1/2] const arrCount = arrIng.slice(0, unitIndex); let count; // if we have just 1 number ( no fractions after) count = arrIng[0] if(arrCount.length === 1){ count = eval(arrIng[0].replace('-', '+')); } // otherwise (ex: 4 1/2) combine those two strings else{ // make it so 4 1/2 = eval = 4.5 count = eval(arrIng.slice(0, unitIndex).join('+')); } objIng = { //count = count count, unit: arrIng[unitIndex], // starts right after the unit ingredient: arrIng.slice(unitIndex + 1).join(' ') }; } //there is no unit but the first position is a number(example 1 packet of active dry yeast) else if(parseInt(arrIng[0], 10)){ objIng = { count: parseInt(arrIng[0], 10), unit: '', // entire array except the first element ingredient: arrIng.slice(1).join(' ') } } // there is no unit and no number in the first position else if (unitIndex === -1){ objIng = { count: 1, unit: '', // ingredient: ingredient ingredient } } return objIng; }); this.ingredients = newIngredients; }
parseIngredients(){ // need to put words with S first, so that it doesnt partially replace our unitsLong words const unitsLong = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds']; const unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound']; //starts our array with the items inside of unitsShort const units = [...unitsShort, 'kg', 'g'] // function that changes our strings to seperate const newIngredients = this.ingredients.map(el => { // uniform units of measurements let ingredient = el.toLowerCase(); // if we find any of the unitsLong words, we replace it with the same positioned unitsShort abbreviation unitsLong.forEach((unit, i) => { ingredient = ingredient.replace(unit, unitsShort[i]); }); // remove parentheses with regular expression, we replace parentheses with a space ingredient = ingredient.replace(/ *\([^)]*\) */g, " "); // parse ingredients into count, unit and ingredient const arrIng = ingredient.split(' '); // find the index, where the unit is located, indexOf() doesnt work here b/c we dont know what unit were looking for // includes - returns true if the element were passing is in the units array const unitIndex = arrIng.findIndex(el2 => units.includes(el2)); // if there is an unit let objIng; if(unitIndex > -1){ // array ingredients, sliced from the beginning until the unitIndex excluding //example: 4 1/2 cups = arrCount is [4,1/2] const arrCount = arrIng.slice(0, unitIndex); let count; // if we have just 1 number ( no fractions after) count = arrIng[0] if(arrCount.length === 1){ count = eval(arrIng[0].replace('-', '+')); } // otherwise (ex: 4 1/2) combine those two strings else{ // make it so 4 1/2 = eval = 4.5 count = eval(arrIng.slice(0, unitIndex).join('+')); } objIng = { //count = count count, unit: arrIng[unitIndex], // starts right after the unit ingredient: arrIng.slice(unitIndex + 1).join(' ') }; } //there is no unit but the first position is a number(example 1 packet of active dry yeast) else if(parseInt(arrIng[0], 10)){ objIng = { count: parseInt(arrIng[0], 10), unit: '', // entire array except the first element ingredient: arrIng.slice(1).join(' ') } } // there is no unit and no number in the first position else if (unitIndex === -1){ objIng = { count: 1, unit: '', // ingredient: ingredient ingredient } } return objIng; }); this.ingredients = newIngredients; }
JavaScript
updateServings(type){ //Servings // ternary operator: if its (dec)decreasing this.servings - 1, otherwise this.servings + 1 const newServings = type === 'dec' ? this.servings -1 : this.servings + 1; //Ingredients //ing: current value of foreach loop this.ingredients.forEach(ing => { ing.count = ing.count * (newServings / this.servings); }) this.servings = newServings; }
updateServings(type){ //Servings // ternary operator: if its (dec)decreasing this.servings - 1, otherwise this.servings + 1 const newServings = type === 'dec' ? this.servings -1 : this.servings + 1; //Ingredients //ing: current value of foreach loop this.ingredients.forEach(ing => { ing.count = ing.count * (newServings / this.servings); }) this.servings = newServings; }
JavaScript
function createHeroSection() { const $h1 = document.querySelector('h1'); const $headerImg = $h1.parentElement.querySelector('img'); if ($headerImg) { const src = $headerImg.getAttribute('src'); const $wrapper = $headerImg.closest('.section-wrapper'); $wrapper.style.backgroundImage = `url(${src})`; $wrapper.classList.add('hero'); $headerImg.parentNode.remove(); } }
function createHeroSection() { const $h1 = document.querySelector('h1'); const $headerImg = $h1.parentElement.querySelector('img'); if ($headerImg) { const src = $headerImg.getAttribute('src'); const $wrapper = $headerImg.closest('.section-wrapper'); $wrapper.style.backgroundImage = `url(${src})`; $wrapper.classList.add('hero'); $headerImg.parentNode.remove(); } }
JavaScript
function createTieredPseudoClasses(style, pseudoClassStyles) { var tieredPseudoClasses = {} // the two-level map for(var key in pseudoClassStyles) { var value = pseudoClassStyles[key] // split key into pseudoclass list var pseudoClassList = key.split(":") var emulatablePseudoClasses = [] var nonEmulatablePseudoClasses = [] for(var n in pseudoClassList) { var pseudoClass = pseudoClassList[n] var pseudoClassParts = getPseudoClassParts(pseudoClass) if(pseudoClassParts.class in emulatedPseudoClasses) { emulatablePseudoClasses.push(pseudoClass) } else { nonEmulatablePseudoClasses.push(pseudoClass) } } // todo: add a third branch as an optimization: if the Style can be rendered without emulation - do that if(emulatablePseudoClasses.length === 0) { // if none of the pseudoclasses can be emulated using javascript validatePurePseudoClassStyles(key, value) // then validate the value and createPseudoClassRules(style, key, '.'+style.className+":"+key, value) // create pseudoClassRules } else { // if some of the pseudoclasses can be emulated using javascript emulatablePseudoClasses.sort() var emulatablePseudoClassKey = emulatablePseudoClasses.join(':') if(tieredPseudoClasses[emulatablePseudoClassKey] === undefined) tieredPseudoClasses[emulatablePseudoClassKey] = {} if(nonEmulatablePseudoClasses.length === 0) { utils.merge(tieredPseudoClasses[emulatablePseudoClassKey], value) } else { nonEmulatablePseudoClasses.sort() var nonEmulatablePsuedoClassKey = nonEmulatablePseudoClasses.join(':') var secondTier = {} secondTier['$$'+nonEmulatablePsuedoClassKey] = value utils.merge(tieredPseudoClasses[emulatablePseudoClassKey], secondTier) } } } return tieredPseudoClasses }
function createTieredPseudoClasses(style, pseudoClassStyles) { var tieredPseudoClasses = {} // the two-level map for(var key in pseudoClassStyles) { var value = pseudoClassStyles[key] // split key into pseudoclass list var pseudoClassList = key.split(":") var emulatablePseudoClasses = [] var nonEmulatablePseudoClasses = [] for(var n in pseudoClassList) { var pseudoClass = pseudoClassList[n] var pseudoClassParts = getPseudoClassParts(pseudoClass) if(pseudoClassParts.class in emulatedPseudoClasses) { emulatablePseudoClasses.push(pseudoClass) } else { nonEmulatablePseudoClasses.push(pseudoClass) } } // todo: add a third branch as an optimization: if the Style can be rendered without emulation - do that if(emulatablePseudoClasses.length === 0) { // if none of the pseudoclasses can be emulated using javascript validatePurePseudoClassStyles(key, value) // then validate the value and createPseudoClassRules(style, key, '.'+style.className+":"+key, value) // create pseudoClassRules } else { // if some of the pseudoclasses can be emulated using javascript emulatablePseudoClasses.sort() var emulatablePseudoClassKey = emulatablePseudoClasses.join(':') if(tieredPseudoClasses[emulatablePseudoClassKey] === undefined) tieredPseudoClasses[emulatablePseudoClassKey] = {} if(nonEmulatablePseudoClasses.length === 0) { utils.merge(tieredPseudoClasses[emulatablePseudoClassKey], value) } else { nonEmulatablePseudoClasses.sort() var nonEmulatablePsuedoClassKey = nonEmulatablePseudoClasses.join(':') var secondTier = {} secondTier['$$'+nonEmulatablePsuedoClassKey] = value utils.merge(tieredPseudoClasses[emulatablePseudoClassKey], secondTier) } } } return tieredPseudoClasses }
JavaScript
function cssValue(cssStyleName, value) { // If a number was passed in, add 'px' to the (except for certain CSS properties) [also taken from jquery's code] if(typeof(value) === "number" && cssNumber[cssStyleName] === undefined) { return value+"px" } else { return value.toString() } }
function cssValue(cssStyleName, value) { // If a number was passed in, add 'px' to the (except for certain CSS properties) [also taken from jquery's code] if(typeof(value) === "number" && cssNumber[cssStyleName] === undefined) { return value+"px" } else { return value.toString() } }
JavaScript
function validatePurePseudoClassStyles(pseudoClass, pseudoClassStyles) { for(var key in pseudoClassStyles) { var value = pseudoClassStyles[key] if(isStyleObject(value)) { throw new Error("Can't set the pseudoclasses '"+pseudoClass+"' to a Style object") } else if(key === '$setup') { throw new Error("$setup can't be used within the pseudoclasses '"+pseudoClass+"'") } else if(key === '$kill') { throw new Error("$kill can't be used within the pseudoclasses '"+pseudoClass+"'") } else if(key.indexOf('$') === 0) { // label style throw new Error("Block labels can't be used within the pseudoclasses '"+pseudoClass+"'") } } }
function validatePurePseudoClassStyles(pseudoClass, pseudoClassStyles) { for(var key in pseudoClassStyles) { var value = pseudoClassStyles[key] if(isStyleObject(value)) { throw new Error("Can't set the pseudoclasses '"+pseudoClass+"' to a Style object") } else if(key === '$setup') { throw new Error("$setup can't be used within the pseudoclasses '"+pseudoClass+"'") } else if(key === '$kill') { throw new Error("$kill can't be used within the pseudoclasses '"+pseudoClass+"'") } else if(key.indexOf('$') === 0) { // label style throw new Error("Block labels can't be used within the pseudoclasses '"+pseudoClass+"'") } } }
JavaScript
function cssClassSheetIndex(classname) { var result = undefined var styleNodes = document.querySelectorAll("style") for(var n=0; n<styleNodes.length; n++) { var sheet = styleNodes[n].sheet jssModule.defaultSheet = sheet var defaultStyleMaybe = jssModule.get(classname) if(Object.keys(defaultStyleMaybe).length > 0) { result = n break } } jssModule.defaultSheet = undefined return result }
function cssClassSheetIndex(classname) { var result = undefined var styleNodes = document.querySelectorAll("style") for(var n=0; n<styleNodes.length; n++) { var sheet = styleNodes[n].sheet jssModule.defaultSheet = sheet var defaultStyleMaybe = jssModule.get(classname) if(Object.keys(defaultStyleMaybe).length > 0) { result = n break } } jssModule.defaultSheet = undefined return result }
JavaScript
function applyStateHandler(component, style) { if(style !== undefined && style.stateHandler !== undefined) { // todo: using setCurrentStyle is a stopgap until I can implement better style application for $state and pseudoclasses (which probably will require a rewrite of much of the style logic) setCurrentStyle(component, style.stateHandler(component.state.subject)) component.state.on('change', function() { setCurrentStyle(component, style.stateHandler(component.state.subject)) }) } }
function applyStateHandler(component, style) { if(style !== undefined && style.stateHandler !== undefined) { // todo: using setCurrentStyle is a stopgap until I can implement better style application for $state and pseudoclasses (which probably will require a rewrite of much of the style logic) setCurrentStyle(component, style.stateHandler(component.state.subject)) component.state.on('change', function() { setCurrentStyle(component, style.stateHandler(component.state.subject)) }) } }
JavaScript
function remove(array, item) { var index = array.indexOf(item) if(index !== -1) array.splice(index, 1) // no longer throwing Error("Item doesn't exist to remove") if there's nothing to remove - in the case that mainTester.timeouts gets set back to [] (when done), it won't be there }
function remove(array, item) { var index = array.indexOf(item) if(index !== -1) array.splice(index, 1) // no longer throwing Error("Item doesn't exist to remove") if there's nothing to remove - in the case that mainTester.timeouts gets set back to [] (when done), it won't be there }
JavaScript
function mapException(exception, warningHandler) { try { if(exception instanceof Error) { var stacktrace; return options.getExceptionInfo(exception).then(function(trace){ stacktrace = trace var smcFutures = [] for(var n=0; n<trace.length; n++) { if(trace[n].file !== undefined) { smcFutures.push(getSourceMapConsumer(trace[n].file, warningHandler)) } else { smcFutures.push(Future(undefined)) } } return Future.all(smcFutures) }).then(function(sourceMapConsumers) { var CustomMappedException = proto(MappedException, function() { // set the name so it looks like the original exception when printed // this subclasses MappedException so that name won't be an own-property this.name = exception.name }) try { throw CustomMappedException(exception, stacktrace, sourceMapConsumers) // IE doesn't give exceptions stack traces unless they're actually thrown } catch(mappedExcetion) { return Future(mappedExcetion) } }) } else { return Future(exception) } } catch(e) { var errorFuture = new Future errorFuture.throw(e) return errorFuture } }
function mapException(exception, warningHandler) { try { if(exception instanceof Error) { var stacktrace; return options.getExceptionInfo(exception).then(function(trace){ stacktrace = trace var smcFutures = [] for(var n=0; n<trace.length; n++) { if(trace[n].file !== undefined) { smcFutures.push(getSourceMapConsumer(trace[n].file, warningHandler)) } else { smcFutures.push(Future(undefined)) } } return Future.all(smcFutures) }).then(function(sourceMapConsumers) { var CustomMappedException = proto(MappedException, function() { // set the name so it looks like the original exception when printed // this subclasses MappedException so that name won't be an own-property this.name = exception.name }) try { throw CustomMappedException(exception, stacktrace, sourceMapConsumers) // IE doesn't give exceptions stack traces unless they're actually thrown } catch(mappedExcetion) { return Future(mappedExcetion) } }) } else { return Future(exception) } } catch(e) { var errorFuture = new Future errorFuture.throw(e) return errorFuture } }
JavaScript
function findFullSourceLine(fileLines, startLine) { var lines = [] var parenCount = 0 var mode = 0 // mode 0 for paren searching, mode 1 for double-quote searching, mode 2 for single-quote searching var lastWasBackslash = false // used for quote searching for(var n=startLine; n<fileLines.length; n++) { var line = fileLines[n] lines.push(line.trim()) for(var i=0; i<line.length; i++) { var c = line[i] if(mode === 0) { if(c === '(') { parenCount++ //if(parenCount === 0) { // return lines.join('\n') // done //} } else if(c === ')' && parenCount > 0) { parenCount-- if(parenCount === 0) { return lines.join('\n') // done } } else if(c === '"') { mode = 1 } else if(c === "'") { mode = 2 } } else if(mode === 1) { if(c === '"' && !lastWasBackslash) { mode = 0 } lastWasBackslash = c==='\\' } else { // mode === 2 if(c === "'" && !lastWasBackslash) { mode = 0 } lastWasBackslash = c==='\\' } } } return lines.join('\n') // if it gets here, something minor went wrong }
function findFullSourceLine(fileLines, startLine) { var lines = [] var parenCount = 0 var mode = 0 // mode 0 for paren searching, mode 1 for double-quote searching, mode 2 for single-quote searching var lastWasBackslash = false // used for quote searching for(var n=startLine; n<fileLines.length; n++) { var line = fileLines[n] lines.push(line.trim()) for(var i=0; i<line.length; i++) { var c = line[i] if(mode === 0) { if(c === '(') { parenCount++ //if(parenCount === 0) { // return lines.join('\n') // done //} } else if(c === ')' && parenCount > 0) { parenCount-- if(parenCount === 0) { return lines.join('\n') // done } } else if(c === '"') { mode = 1 } else if(c === "'") { mode = 2 } } else if(mode === 1) { if(c === '"' && !lastWasBackslash) { mode = 0 } lastWasBackslash = c==='\\' } else { // mode === 2 if(c === "'" && !lastWasBackslash) { mode = 0 } lastWasBackslash = c==='\\' } } } return lines.join('\n') // if it gets here, something minor went wrong }