-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
prebid.js
1028 lines (895 loc) · 41 KB
/
prebid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @module pbjs */
import { getGlobal } from './prebidGlobal.js';
import {
adUnitsFilter, flatten, getHighestCpm, isArrayOfNums, isGptPubadsDefined, uniques, logInfo,
contains, logError, isArray, deepClone, deepAccess, isNumber, logWarn, logMessage, isFn,
transformAdServerTargetingObj, bind, replaceAuctionPrice, replaceClickThrough, insertElement,
inIframe, callBurl, createInvisibleIframe, generateUUID, unsupportedBidderMessage, isEmpty, mergeDeep, deepSetValue
} from './utils.js';
import { listenMessagesFromCreative } from './secureCreatives.js';
import { userSync } from './userSync.js';
import { config } from './config.js';
import { auctionManager } from './auctionManager.js';
import { filters, targeting } from './targeting.js';
import {hook, wrapHook} from './hook.js';
import { loadSession } from './debugging.js';
import {includes} from './polyfill.js';
import { adunitCounter } from './adUnits.js';
import { executeRenderer, isRendererRequired } from './Renderer.js';
import { createBid } from './bidfactory.js';
import { storageCallbacks } from './storageManager.js';
import { emitAdRenderSucceeded, emitAdRenderFail } from './adRendering.js';
import {gdprDataHandler, getS2SBidderSet, uspDataHandler, default as adapterManager} from './adapterManager.js';
import CONSTANTS from './constants.json';
import * as events from './events.js'
const $$PREBID_GLOBAL$$ = getGlobal();
const { triggerUserSyncs } = userSync;
/* private variables */
const { ADD_AD_UNITS, BID_WON, REQUEST_BIDS, SET_TARGETING, STALE_RENDER } = CONSTANTS.EVENTS;
const { PREVENT_WRITING_ON_MAIN_DOCUMENT, NO_AD, EXCEPTION, CANNOT_FIND_AD, MISSING_DOC_OR_ADID } = CONSTANTS.AD_RENDER_FAILED_REASON;
const eventValidators = {
bidWon: checkDefinedPlacement
};
// initialize existing debugging sessions if present
loadSession();
/* Public vars */
$$PREBID_GLOBAL$$.bidderSettings = $$PREBID_GLOBAL$$.bidderSettings || {};
// let the world know we are loaded
$$PREBID_GLOBAL$$.libLoaded = true;
// version auto generated from build
$$PREBID_GLOBAL$$.version = 'v$prebid.version$';
logInfo('Prebid.js v$prebid.version$ loaded');
$$PREBID_GLOBAL$$.installedModules = $$PREBID_GLOBAL$$.installedModules || [];
// create adUnit array
$$PREBID_GLOBAL$$.adUnits = $$PREBID_GLOBAL$$.adUnits || [];
// Allow publishers who enable user sync override to trigger their sync
$$PREBID_GLOBAL$$.triggerUserSyncs = triggerUserSyncs;
function checkDefinedPlacement(id) {
var adUnitCodes = auctionManager.getBidsRequested().map(bidSet => bidSet.bids.map(bid => bid.adUnitCode))
.reduce(flatten)
.filter(uniques);
if (!contains(adUnitCodes, id)) {
logError('The "' + id + '" placement is not defined.');
return;
}
return true;
}
function setRenderSize(doc, width, height) {
if (doc.defaultView && doc.defaultView.frameElement) {
doc.defaultView.frameElement.width = width;
doc.defaultView.frameElement.height = height;
}
}
function validateSizes(sizes, targLength) {
let cleanSizes = [];
if (isArray(sizes) && ((targLength) ? sizes.length === targLength : sizes.length > 0)) {
// check if an array of arrays or array of numbers
if (sizes.every(sz => isArrayOfNums(sz, 2))) {
cleanSizes = sizes;
} else if (isArrayOfNums(sizes, 2)) {
cleanSizes.push(sizes);
}
}
return cleanSizes;
}
function validateBannerMediaType(adUnit) {
const validatedAdUnit = deepClone(adUnit);
const banner = validatedAdUnit.mediaTypes.banner;
const bannerSizes = validateSizes(banner.sizes);
if (bannerSizes.length > 0) {
banner.sizes = bannerSizes;
// Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.banner.sizes
validatedAdUnit.sizes = bannerSizes;
} else {
logError('Detected a mediaTypes.banner object without a proper sizes field. Please ensure the sizes are listed like: [[300, 250], ...]. Removing invalid mediaTypes.banner object from request.');
delete validatedAdUnit.mediaTypes.banner
}
return validatedAdUnit;
}
function validateVideoMediaType(adUnit) {
const validatedAdUnit = deepClone(adUnit);
const video = validatedAdUnit.mediaTypes.video;
if (video.playerSize) {
let tarPlayerSizeLen = (typeof video.playerSize[0] === 'number') ? 2 : 1;
const videoSizes = validateSizes(video.playerSize, tarPlayerSizeLen);
if (videoSizes.length > 0) {
if (tarPlayerSizeLen === 2) {
logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.');
}
video.playerSize = videoSizes;
// Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.video.playerSize
validatedAdUnit.sizes = videoSizes;
} else {
logError('Detected incorrect configuration of mediaTypes.video.playerSize. Please specify only one set of dimensions in a format like: [[640, 480]]. Removing invalid mediaTypes.video.playerSize property from request.');
delete validatedAdUnit.mediaTypes.video.playerSize;
}
}
return validatedAdUnit;
}
function validateNativeMediaType(adUnit) {
const validatedAdUnit = deepClone(adUnit);
const native = validatedAdUnit.mediaTypes.native;
// if native assets are specified in OpenRTB format, remove legacy assets and print a warn.
if (native.ortb) {
const legacyNativeKeys = Object.keys(CONSTANTS.NATIVE_KEYS).filter(key => CONSTANTS.NATIVE_KEYS[key].includes('hb_native_'));
const nativeKeys = Object.keys(native);
const intersection = nativeKeys.filter(nativeKey => legacyNativeKeys.includes(nativeKey));
if (intersection.length > 0) {
logError(`when using native OpenRTB format, you cannot use legacy native properties. Deleting ${intersection} keys from request.`);
intersection.forEach(legacyKey => delete validatedAdUnit.mediaTypes.native[legacyKey]);
}
}
if (native.image && native.image.sizes && !Array.isArray(native.image.sizes)) {
logError('Please use an array of sizes for native.image.sizes field. Removing invalid mediaTypes.native.image.sizes property from request.');
delete validatedAdUnit.mediaTypes.native.image.sizes;
}
if (native.image && native.image.aspect_ratios && !Array.isArray(native.image.aspect_ratios)) {
logError('Please use an array of sizes for native.image.aspect_ratios field. Removing invalid mediaTypes.native.image.aspect_ratios property from request.');
delete validatedAdUnit.mediaTypes.native.image.aspect_ratios;
}
if (native.icon && native.icon.sizes && !Array.isArray(native.icon.sizes)) {
logError('Please use an array of sizes for native.icon.sizes field. Removing invalid mediaTypes.native.icon.sizes property from request.');
delete validatedAdUnit.mediaTypes.native.icon.sizes;
}
return validatedAdUnit;
}
function validateAdUnitPos(adUnit, mediaType) {
let pos = deepAccess(adUnit, `mediaTypes.${mediaType}.pos`);
if (!isNumber(pos) || isNaN(pos) || !isFinite(pos)) {
let warning = `Value of property 'pos' on ad unit ${adUnit.code} should be of type: Number`;
logWarn(warning);
events.emit(CONSTANTS.EVENTS.AUCTION_DEBUG, {type: 'WARNING', arguments: warning});
delete adUnit.mediaTypes[mediaType].pos;
}
return adUnit
}
function validateAdUnit(adUnit) {
const msg = (msg) => `adUnit.code '${adUnit.code}' ${msg}`;
const mediaTypes = adUnit.mediaTypes;
const bids = adUnit.bids;
if (bids != null && !isArray(bids)) {
logError(msg(`defines 'adUnit.bids' that is not an array. Removing adUnit from auction`));
return null;
}
if (bids == null && adUnit.ortb2Imp == null) {
logError(msg(`has no 'adUnit.bids' and no 'adUnit.ortb2Imp'. Removing adUnit from auction`));
return null;
}
if (!mediaTypes || Object.keys(mediaTypes).length === 0) {
logError(msg(`does not define a 'mediaTypes' object. This is a required field for the auction, so this adUnit has been removed.`));
return null;
}
if (adUnit.ortb2Imp != null && (bids == null || bids.length === 0)) {
adUnit.bids = [{bidder: null}]; // the 'null' bidder is treated as an s2s-only placeholder by adapterManager
logMessage(msg(`defines 'adUnit.ortb2Imp' with no 'adUnit.bids'; it will be seen only by S2S adapters`));
}
return adUnit;
}
export const adUnitSetupChecks = {
validateAdUnit,
validateBannerMediaType,
validateVideoMediaType,
validateSizes
};
if (FEATURES.NATIVE) {
Object.assign(adUnitSetupChecks, {validateNativeMediaType});
}
export const checkAdUnitSetup = hook('sync', function (adUnits) {
const validatedAdUnits = [];
adUnits.forEach(adUnit => {
adUnit = validateAdUnit(adUnit);
if (adUnit == null) return;
const mediaTypes = adUnit.mediaTypes;
let validatedBanner, validatedVideo, validatedNative;
if (mediaTypes.banner) {
validatedBanner = validateBannerMediaType(adUnit);
if (mediaTypes.banner.hasOwnProperty('pos')) validatedBanner = validateAdUnitPos(validatedBanner, 'banner');
}
if (mediaTypes.video) {
validatedVideo = validatedBanner ? validateVideoMediaType(validatedBanner) : validateVideoMediaType(adUnit);
if (mediaTypes.video.hasOwnProperty('pos')) validatedVideo = validateAdUnitPos(validatedVideo, 'video');
}
if (FEATURES.NATIVE && mediaTypes.native) {
validatedNative = validatedVideo ? validateNativeMediaType(validatedVideo) : validatedBanner ? validateNativeMediaType(validatedBanner) : validateNativeMediaType(adUnit);
}
const validatedAdUnit = Object.assign({}, validatedBanner, validatedVideo, validatedNative);
validatedAdUnits.push(validatedAdUnit);
});
return validatedAdUnits;
}, 'checkAdUnitSetup');
/// ///////////////////////////////
// //
// Start Public APIs //
// //
/// ///////////////////////////////
/**
* This function returns the query string targeting parameters available at this moment for a given ad unit. Note that some bidder's response may not have been received if you call this function too quickly after the requests are sent.
* @param {string} [adunitCode] adUnitCode to get the bid responses for
* @alias module:pbjs.getAdserverTargetingForAdUnitCodeStr
* @return {Array} returnObj return bids array
*/
$$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr = function (adunitCode) {
logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCodeStr', arguments);
// call to retrieve bids array
if (adunitCode) {
var res = $$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode(adunitCode);
return transformAdServerTargetingObj(res);
} else {
logMessage('Need to call getAdserverTargetingForAdUnitCodeStr with adunitCode');
}
};
/**
* This function returns the query string targeting parameters available at this moment for a given ad unit. Note that some bidder's response may not have been received if you call this function too quickly after the requests are sent.
* @param adUnitCode {string} adUnitCode to get the bid responses for
* @alias module:pbjs.getHighestUnusedBidResponseForAdUnitCode
* @returns {Object} returnObj return bid
*/
$$PREBID_GLOBAL$$.getHighestUnusedBidResponseForAdUnitCode = function (adunitCode) {
if (adunitCode) {
const bid = auctionManager.getAllBidsForAdUnitCode(adunitCode)
.filter(filters.isUnusedBid)
.filter(filters.isBidNotExpired)
return bid.length ? bid.reduce(getHighestCpm) : {}
} else {
logMessage('Need to call getHighestUnusedBidResponseForAdUnitCode with adunitCode');
}
};
/**
* This function returns the query string targeting parameters available at this moment for a given ad unit. Note that some bidder's response may not have been received if you call this function too quickly after the requests are sent.
* @param adUnitCode {string} adUnitCode to get the bid responses for
* @alias module:pbjs.getAdserverTargetingForAdUnitCode
* @returns {Object} returnObj return bids
*/
$$PREBID_GLOBAL$$.getAdserverTargetingForAdUnitCode = function (adUnitCode) {
return $$PREBID_GLOBAL$$.getAdserverTargeting(adUnitCode)[adUnitCode];
};
/**
* returns all ad server targeting for all ad units
* @return {Object} Map of adUnitCodes and targeting values []
* @alias module:pbjs.getAdserverTargeting
*/
$$PREBID_GLOBAL$$.getAdserverTargeting = function (adUnitCode) {
logInfo('Invoking $$PREBID_GLOBAL$$.getAdserverTargeting', arguments);
return targeting.getAllTargeting(adUnitCode);
};
/**
* returns all consent data
* @return {Object} Map of consent types and data
* @alias module:pbjs.getConsentData
*/
function getConsentMetadata() {
return {
gdpr: gdprDataHandler.getConsentMeta(),
usp: uspDataHandler.getConsentMeta(),
coppa: !!(config.getConfig('coppa'))
}
}
$$PREBID_GLOBAL$$.getConsentMetadata = function () {
logInfo('Invoking $$PREBID_GLOBAL$$.getConsentMetadata');
return getConsentMetadata();
};
function getBids(type) {
const responses = auctionManager[type]()
.filter(bind.call(adUnitsFilter, this, auctionManager.getAdUnitCodes()));
// find the last auction id to get responses for most recent auction only
const currentAuctionId = auctionManager.getLastAuctionId();
return responses
.map(bid => bid.adUnitCode)
.filter(uniques).map(adUnitCode => responses
.filter(bid => bid.auctionId === currentAuctionId && bid.adUnitCode === adUnitCode))
.filter(bids => bids && bids[0] && bids[0].adUnitCode)
.map(bids => {
return {
[bids[0].adUnitCode]: { bids }
};
})
.reduce((a, b) => Object.assign(a, b), {});
}
/**
* This function returns the bids requests involved in an auction but not bid on
* @alias module:pbjs.getNoBids
* @return {Object} map | object that contains the bidRequests
*/
$$PREBID_GLOBAL$$.getNoBids = function () {
logInfo('Invoking $$PREBID_GLOBAL$$.getNoBids', arguments);
return getBids('getNoBids');
};
/**
* This function returns the bids requests involved in an auction but not bid on or the specified adUnitCode
* @param {string} adUnitCode adUnitCode
* @alias module:pbjs.getNoBidsForAdUnitCode
* @return {Object} bidResponse object
*/
$$PREBID_GLOBAL$$.getNoBidsForAdUnitCode = function (adUnitCode) {
const bids = auctionManager.getNoBids().filter(bid => bid.adUnitCode === adUnitCode);
return { bids };
};
/**
* This function returns the bid responses at the given moment.
* @alias module:pbjs.getBidResponses
* @return {Object} map | object that contains the bidResponses
*/
$$PREBID_GLOBAL$$.getBidResponses = function () {
logInfo('Invoking $$PREBID_GLOBAL$$.getBidResponses', arguments);
return getBids('getBidsReceived');
};
/**
* Returns bidResponses for the specified adUnitCode
* @param {string} adUnitCode adUnitCode
* @alias module:pbjs.getBidResponsesForAdUnitCode
* @return {Object} bidResponse object
*/
$$PREBID_GLOBAL$$.getBidResponsesForAdUnitCode = function (adUnitCode) {
const bids = auctionManager.getBidsReceived().filter(bid => bid.adUnitCode === adUnitCode);
return { bids };
};
/**
* Set query string targeting on one or more GPT ad units.
* @param {(string|string[])} adUnit a single `adUnit.code` or multiple.
* @param {function(object)} customSlotMatching gets a GoogleTag slot and returns a filter function for adUnitCode, so you can decide to match on either eg. return slot => { return adUnitCode => { return slot.getSlotElementId() === 'myFavoriteDivId'; } };
* @alias module:pbjs.setTargetingForGPTAsync
*/
$$PREBID_GLOBAL$$.setTargetingForGPTAsync = function (adUnit, customSlotMatching) {
logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForGPTAsync', arguments);
if (!isGptPubadsDefined()) {
logError('window.googletag is not defined on the page');
return;
}
// get our ad unit codes
let targetingSet = targeting.getAllTargeting(adUnit);
// first reset any old targeting
targeting.resetPresetTargeting(adUnit, customSlotMatching);
// now set new targeting keys
targeting.setTargetingForGPT(targetingSet, customSlotMatching);
Object.keys(targetingSet).forEach((adUnitCode) => {
Object.keys(targetingSet[adUnitCode]).forEach((targetingKey) => {
if (targetingKey === 'hb_adid') {
auctionManager.setStatusForBids(targetingSet[adUnitCode][targetingKey], CONSTANTS.BID_STATUS.BID_TARGETING_SET);
}
});
});
// emit event
events.emit(SET_TARGETING, targetingSet);
};
/**
* Set query string targeting on all AST (AppNexus Seller Tag) ad units. Note that this function has to be called after all ad units on page are defined. For working example code, see [Using Prebid.js with AppNexus Publisher Ad Server](http://prebid.org/dev-docs/examples/use-prebid-with-appnexus-ad-server.html).
* @param {(string|string[])} adUnitCode adUnitCode or array of adUnitCodes
* @alias module:pbjs.setTargetingForAst
*/
$$PREBID_GLOBAL$$.setTargetingForAst = function (adUnitCodes) {
logInfo('Invoking $$PREBID_GLOBAL$$.setTargetingForAn', arguments);
if (!targeting.isApntagDefined()) {
logError('window.apntag is not defined on the page');
return;
}
targeting.setTargetingForAst(adUnitCodes);
// emit event
events.emit(SET_TARGETING, targeting.getAllTargeting());
};
/**
* This function will check for presence of given node in given parent. If not present - will inject it.
* @param {Node} node node, whose existance is in question
* @param {Document} doc document element do look in
* @param {string} tagName tag name to look in
*/
function reinjectNodeIfRemoved(node, doc, tagName) {
const injectionNode = doc.querySelector(tagName);
if (!node.parentNode || node.parentNode !== injectionNode) {
insertElement(node, doc, tagName);
}
}
/**
* This function will render the ad (based on params) in the given iframe document passed through.
* Note that doc SHOULD NOT be the parent document page as we can't doc.write() asynchronously
* @param {Document} doc document
* @param {string} id bid id to locate the ad
* @alias module:pbjs.renderAd
*/
$$PREBID_GLOBAL$$.renderAd = hook('async', function (doc, id, options) {
logInfo('Invoking $$PREBID_GLOBAL$$.renderAd', arguments);
logMessage('Calling renderAd with adId :' + id);
if (doc && id) {
try {
// lookup ad by ad Id
const bid = auctionManager.findBidByAdId(id);
if (bid) {
let shouldRender = true;
if (bid && bid.status === CONSTANTS.BID_STATUS.RENDERED) {
logWarn(`Ad id ${bid.adId} has been rendered before`);
events.emit(STALE_RENDER, bid);
if (deepAccess(config.getConfig('auctionOptions'), 'suppressStaleRender')) {
shouldRender = false;
}
}
if (shouldRender) {
// replace macros according to openRTB with price paid = bid.cpm
bid.ad = replaceAuctionPrice(bid.ad, bid.originalCpm || bid.cpm);
bid.adUrl = replaceAuctionPrice(bid.adUrl, bid.originalCpm || bid.cpm);
// replacing clickthrough if submitted
if (options && options.clickThrough) {
const {clickThrough} = options;
bid.ad = replaceClickThrough(bid.ad, clickThrough);
bid.adUrl = replaceClickThrough(bid.adUrl, clickThrough);
}
// save winning bids
auctionManager.addWinningBid(bid);
// emit 'bid won' event here
events.emit(BID_WON, bid);
const {height, width, ad, mediaType, adUrl, renderer} = bid;
const creativeComment = document.createComment(`Creative ${bid.creativeId} served by ${bid.bidder} Prebid.js Header Bidding`);
insertElement(creativeComment, doc, 'html');
if (isRendererRequired(renderer)) {
executeRenderer(renderer, bid, doc);
reinjectNodeIfRemoved(creativeComment, doc, 'html');
emitAdRenderSucceeded({ doc, bid, id });
} else if ((doc === document && !inIframe()) || mediaType === 'video') {
const message = `Error trying to write ad. Ad render call ad id ${id} was prevented from writing to the main document.`;
emitAdRenderFail({reason: PREVENT_WRITING_ON_MAIN_DOCUMENT, message, bid, id});
} else if (ad) {
doc.write(ad);
doc.close();
setRenderSize(doc, width, height);
reinjectNodeIfRemoved(creativeComment, doc, 'html');
callBurl(bid);
emitAdRenderSucceeded({ doc, bid, id });
} else if (adUrl) {
const iframe = createInvisibleIframe();
iframe.height = height;
iframe.width = width;
iframe.style.display = 'inline';
iframe.style.overflow = 'hidden';
iframe.src = adUrl;
insertElement(iframe, doc, 'body');
setRenderSize(doc, width, height);
reinjectNodeIfRemoved(creativeComment, doc, 'html');
callBurl(bid);
emitAdRenderSucceeded({ doc, bid, id });
} else {
const message = `Error trying to write ad. No ad for bid response id: ${id}`;
emitAdRenderFail({reason: NO_AD, message, bid, id});
}
}
} else {
const message = `Error trying to write ad. Cannot find ad by given id : ${id}`;
emitAdRenderFail({ reason: CANNOT_FIND_AD, message, id });
}
} catch (e) {
const message = `Error trying to write ad Id :${id} to the page:${e.message}`;
emitAdRenderFail({ reason: EXCEPTION, message, id });
}
} else {
const message = `Error trying to write ad Id :${id} to the page. Missing document or adId`;
emitAdRenderFail({ reason: MISSING_DOC_OR_ADID, message, id });
}
});
/**
* Remove adUnit from the $$PREBID_GLOBAL$$ configuration, if there are no addUnitCode(s) it will remove all
* @param {string| Array} adUnitCode the adUnitCode(s) to remove
* @alias module:pbjs.removeAdUnit
*/
$$PREBID_GLOBAL$$.removeAdUnit = function (adUnitCode) {
logInfo('Invoking $$PREBID_GLOBAL$$.removeAdUnit', arguments);
if (!adUnitCode) {
$$PREBID_GLOBAL$$.adUnits = [];
return;
}
let adUnitCodes;
if (isArray(adUnitCode)) {
adUnitCodes = adUnitCode;
} else {
adUnitCodes = [adUnitCode];
}
adUnitCodes.forEach((adUnitCode) => {
for (let i = $$PREBID_GLOBAL$$.adUnits.length - 1; i >= 0; i--) {
if ($$PREBID_GLOBAL$$.adUnits[i].code === adUnitCode) {
$$PREBID_GLOBAL$$.adUnits.splice(i, 1);
}
}
});
};
/**
* @param {Object} requestOptions
* @param {function} requestOptions.bidsBackHandler
* @param {number} requestOptions.timeout
* @param {Array} requestOptions.adUnits
* @param {Array} requestOptions.adUnitCodes
* @param {Array} requestOptions.labels
* @param {String} requestOptions.auctionId
* @alias module:pbjs.requestBids
*/
$$PREBID_GLOBAL$$.requestBids = (function() {
const delegate = hook('async', function ({ bidsBackHandler, timeout, adUnits, adUnitCodes, labels, auctionId, ortb2 } = {}) {
events.emit(REQUEST_BIDS);
const cbTimeout = timeout || config.getConfig('bidderTimeout');
logInfo('Invoking $$PREBID_GLOBAL$$.requestBids', arguments);
const ortb2Fragments = {
global: mergeDeep({}, config.getAnyConfig('ortb2') || {}, ortb2 || {}),
bidder: Object.fromEntries(Object.entries(config.getBidderConfig()).map(([bidder, cfg]) => [bidder, cfg.ortb2]).filter(([_, ortb2]) => ortb2 != null))
}
return startAuction({bidsBackHandler, timeout: cbTimeout, adUnits, adUnitCodes, labels, auctionId, ortb2Fragments});
}, 'requestBids');
return wrapHook(delegate, function requestBids(req = {}) {
// if the request does not specify adUnits, clone the global adUnit array - before
// any hook has a chance to run.
// otherwise, if the caller goes on to use addAdUnits/removeAdUnits, any asynchronous logic
// in any hook might see their effects.
let adUnits = req.adUnits || $$PREBID_GLOBAL$$.adUnits;
req.adUnits = (isArray(adUnits) ? adUnits.slice() : [adUnits]);
return delegate.call(this, req);
});
})();
export const startAuction = hook('async', function ({ bidsBackHandler, timeout: cbTimeout, adUnits, adUnitCodes, labels, auctionId, ortb2Fragments } = {}) {
const s2sBidders = getS2SBidderSet(config.getConfig('s2sConfig') || []);
adUnits = checkAdUnitSetup(adUnits);
if (adUnitCodes && adUnitCodes.length) {
// if specific adUnitCodes supplied filter adUnits for those codes
adUnits = adUnits.filter(unit => includes(adUnitCodes, unit.code));
} else {
// otherwise derive adUnitCodes from adUnits
adUnitCodes = adUnits && adUnits.map(unit => unit.code);
}
/*
* for a given adunit which supports a set of mediaTypes
* and a given bidder which supports a set of mediaTypes
* a bidder is eligible to participate on the adunit
* if it supports at least one of the mediaTypes on the adunit
*/
adUnits.forEach(adUnit => {
// get the adunit's mediaTypes, defaulting to banner if mediaTypes isn't present
const adUnitMediaTypes = Object.keys(adUnit.mediaTypes || { 'banner': 'banner' });
// get the bidder's mediaTypes
const allBidders = adUnit.bids.map(bid => bid.bidder);
const bidderRegistry = adapterManager.bidderRegistry;
const bidders = allBidders.filter(bidder => !s2sBidders.has(bidder));
adUnit.transactionId = generateUUID();
// Populate ortb2Imp.ext.tid with transactionId. Specifying a transaction ID per item in the ortb impression array, lets multiple transaction IDs be transmitted in a single bid request.
deepSetValue(adUnit, 'ortb2Imp.ext.tid', adUnit.transactionId)
bidders.forEach(bidder => {
const adapter = bidderRegistry[bidder];
const spec = adapter && adapter.getSpec && adapter.getSpec();
// banner is default if not specified in spec
const bidderMediaTypes = (spec && spec.supportedMediaTypes) || ['banner'];
// check if the bidder's mediaTypes are not in the adUnit's mediaTypes
const bidderEligible = adUnitMediaTypes.some(type => includes(bidderMediaTypes, type));
if (!bidderEligible) {
// drop the bidder from the ad unit if it's not compatible
logWarn(unsupportedBidderMessage(adUnit, bidder));
adUnit.bids = adUnit.bids.filter(bid => bid.bidder !== bidder);
} else {
adunitCounter.incrementBidderRequestsCounter(adUnit.code, bidder);
}
});
adunitCounter.incrementRequestsCounter(adUnit.code);
});
if (!adUnits || adUnits.length === 0) {
logMessage('No adUnits configured. No bids requested.');
if (typeof bidsBackHandler === 'function') {
// executeCallback, this will only be called in case of first request
try {
bidsBackHandler();
} catch (e) {
logError('Error executing bidsBackHandler', null, e);
}
}
return;
}
const auction = auctionManager.createAuction({
adUnits,
adUnitCodes,
callback: bidsBackHandler,
cbTimeout,
labels,
auctionId,
ortb2Fragments
});
let adUnitsLen = adUnits.length;
if (adUnitsLen > 15) {
logInfo(`Current auction ${auction.getAuctionId()} contains ${adUnitsLen} adUnits.`, adUnits);
}
adUnitCodes.forEach(code => targeting.setLatestAuctionForAdUnit(code, auction.getAuctionId()));
auction.callBids();
}, 'startAuction');
export function executeCallbacks(fn, reqBidsConfigObj) {
runAll(storageCallbacks);
runAll(enableAnalyticsCallbacks);
fn.call(this, reqBidsConfigObj);
function runAll(queue) {
var queued;
while ((queued = queue.shift())) {
queued();
}
}
}
// This hook will execute all storage callbacks which were registered before gdpr enforcement hook was added. Some bidders, user id modules use storage functions when module is parsed but gdpr enforcement hook is not added at that stage as setConfig callbacks are yet to be called. Hence for such calls we execute all the stored callbacks just before requestBids. At this hook point we will know for sure that gdprEnforcement module is added or not
$$PREBID_GLOBAL$$.requestBids.before(executeCallbacks, 49);
/**
*
* Add adunit(s)
* @param {Array|Object} adUnitArr Array of adUnits or single adUnit Object.
* @alias module:pbjs.addAdUnits
*/
$$PREBID_GLOBAL$$.addAdUnits = function (adUnitArr) {
logInfo('Invoking $$PREBID_GLOBAL$$.addAdUnits', arguments);
$$PREBID_GLOBAL$$.adUnits.push.apply($$PREBID_GLOBAL$$.adUnits, isArray(adUnitArr) ? adUnitArr : [adUnitArr]);
// emit event
events.emit(ADD_AD_UNITS);
};
/**
* @param {string} event the name of the event
* @param {Function} handler a callback to set on event
* @param {string} id an identifier in the context of the event
* @alias module:pbjs.onEvent
*
* This API call allows you to register a callback to handle a Prebid.js event.
* An optional `id` parameter provides more finely-grained event callback registration.
* This makes it possible to register callback events for a specific item in the
* event context. For example, `bidWon` events will accept an `id` for ad unit code.
* `bidWon` callbacks registered with an ad unit code id will be called when a bid
* for that ad unit code wins the auction. Without an `id` this method registers the
* callback for every `bidWon` event.
*
* Currently `bidWon` is the only event that accepts an `id` parameter.
*/
$$PREBID_GLOBAL$$.onEvent = function (event, handler, id) {
logInfo('Invoking $$PREBID_GLOBAL$$.onEvent', arguments);
if (!isFn(handler)) {
logError('The event handler provided is not a function and was not set on event "' + event + '".');
return;
}
if (id && !eventValidators[event].call(null, id)) {
logError('The id provided is not valid for event "' + event + '" and no handler was set.');
return;
}
events.on(event, handler, id);
};
/**
* @param {string} event the name of the event
* @param {Function} handler a callback to remove from the event
* @param {string} id an identifier in the context of the event (see `$$PREBID_GLOBAL$$.onEvent`)
* @alias module:pbjs.offEvent
*/
$$PREBID_GLOBAL$$.offEvent = function (event, handler, id) {
logInfo('Invoking $$PREBID_GLOBAL$$.offEvent', arguments);
if (id && !eventValidators[event].call(null, id)) {
return;
}
events.off(event, handler, id);
};
/**
* Return a copy of all events emitted
*
* @alias module:pbjs.getEvents
*/
$$PREBID_GLOBAL$$.getEvents = function () {
logInfo('Invoking $$PREBID_GLOBAL$$.getEvents');
return events.getEvents();
};
/*
* Wrapper to register bidderAdapter externally (adapterManager.registerBidAdapter())
* @param {Function} bidderAdaptor [description]
* @param {string} bidderCode [description]
* @alias module:pbjs.registerBidAdapter
*/
$$PREBID_GLOBAL$$.registerBidAdapter = function (bidderAdaptor, bidderCode) {
logInfo('Invoking $$PREBID_GLOBAL$$.registerBidAdapter', arguments);
try {
adapterManager.registerBidAdapter(bidderAdaptor(), bidderCode);
} catch (e) {
logError('Error registering bidder adapter : ' + e.message);
}
};
/**
* Wrapper to register analyticsAdapter externally (adapterManager.registerAnalyticsAdapter())
* @param {Object} options [description]
* @alias module:pbjs.registerAnalyticsAdapter
*/
$$PREBID_GLOBAL$$.registerAnalyticsAdapter = function (options) {
logInfo('Invoking $$PREBID_GLOBAL$$.registerAnalyticsAdapter', arguments);
try {
adapterManager.registerAnalyticsAdapter(options);
} catch (e) {
logError('Error registering analytics adapter : ' + e.message);
}
};
/**
* Wrapper to bidfactory.createBid()
* @param {string} statusCode [description]
* @alias module:pbjs.createBid
* @return {Object} bidResponse [description]
*/
$$PREBID_GLOBAL$$.createBid = function (statusCode) {
logInfo('Invoking $$PREBID_GLOBAL$$.createBid', arguments);
return createBid(statusCode);
};
/**
* Enable sending analytics data to the analytics provider of your
* choice.
*
* For usage, see [Integrate with the Prebid Analytics
* API](http://prebid.org/dev-docs/integrate-with-the-prebid-analytics-api.html).
*
* For a list of analytics adapters, see [Analytics for
* Prebid](http://prebid.org/overview/analytics.html).
* @param {Object} config
* @param {string} config.provider The name of the provider, e.g., `"ga"` for Google Analytics.
* @param {Object} config.options The options for this particular analytics adapter. This will likely vary between adapters.
* @alias module:pbjs.enableAnalytics
*/
// Stores 'enableAnalytics' callbacks for later execution.
const enableAnalyticsCallbacks = [];
const enableAnalyticsCb = hook('async', function (config) {
if (config && !isEmpty(config)) {
logInfo('Invoking $$PREBID_GLOBAL$$.enableAnalytics for: ', config);
adapterManager.enableAnalytics(config);
} else {
logError('$$PREBID_GLOBAL$$.enableAnalytics should be called with option {}');
}
}, 'enableAnalyticsCb');
$$PREBID_GLOBAL$$.enableAnalytics = function (config) {
enableAnalyticsCallbacks.push(enableAnalyticsCb.bind(this, config));
};
/**
* @alias module:pbjs.aliasBidder
*/
$$PREBID_GLOBAL$$.aliasBidder = function (bidderCode, alias, options) {
logInfo('Invoking $$PREBID_GLOBAL$$.aliasBidder', arguments);
if (bidderCode && alias) {
adapterManager.aliasBidAdapter(bidderCode, alias, options);
} else {
logError('bidderCode and alias must be passed as arguments', '$$PREBID_GLOBAL$$.aliasBidder');
}
};
/**
* The bid response object returned by an external bidder adapter during the auction.
* @typedef {Object} AdapterBidResponse
* @property {string} pbAg Auto granularity price bucket; CPM <= 5 ? increment = 0.05 : CPM > 5 && CPM <= 10 ? increment = 0.10 : CPM > 10 && CPM <= 20 ? increment = 0.50 : CPM > 20 ? priceCap = 20.00. Example: `"0.80"`.
* @property {string} pbCg Custom price bucket. For example setup, see {@link setPriceGranularity}. Example: `"0.84"`.
* @property {string} pbDg Dense granularity price bucket; CPM <= 3 ? increment = 0.01 : CPM > 3 && CPM <= 8 ? increment = 0.05 : CPM > 8 && CPM <= 20 ? increment = 0.50 : CPM > 20? priceCap = 20.00. Example: `"0.84"`.
* @property {string} pbLg Low granularity price bucket; $0.50 increment, capped at $5, floored to two decimal places. Example: `"0.50"`.
* @property {string} pbMg Medium granularity price bucket; $0.10 increment, capped at $20, floored to two decimal places. Example: `"0.80"`.
* @property {string} pbHg High granularity price bucket; $0.01 increment, capped at $20, floored to two decimal places. Example: `"0.84"`.
*
* @property {string} bidder The string name of the bidder. This *may* be the same as the `bidderCode`. For For a list of all bidders and their codes, see [Bidders' Params](http://prebid.org/dev-docs/bidders.html).
* @property {string} bidderCode The unique string that identifies this bidder. For a list of all bidders and their codes, see [Bidders' Params](http://prebid.org/dev-docs/bidders.html).
*
* @property {string} requestId The [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) representing the bid request.
* @property {number} requestTimestamp The time at which the bid request was sent out, expressed in milliseconds.
* @property {number} responseTimestamp The time at which the bid response was received, expressed in milliseconds.
* @property {number} timeToRespond How long it took for the bidder to respond with this bid, expressed in milliseconds.
*
* @property {string} size The size of the ad creative, expressed in `"AxB"` format, where A and B are numbers of pixels. Example: `"320x50"`.
* @property {string} width The width of the ad creative in pixels. Example: `"320"`.
* @property {string} height The height of the ad creative in pixels. Example: `"50"`.
*
* @property {string} ad The actual ad creative content, often HTML with CSS, JavaScript, and/or links to additional content. Example: `"<div id='beacon_-YQbipJtdxmMCgEPHExLhmqzEm' style='position: absolute; left: 0px; top: 0px; visibility: hidden;'><img src='http://aplus-...'/></div><iframe src=\"http://aax-us-east.amazon-adsystem.com/e/is/8dcfcd..." width=\"728\" height=\"90\" frameborder=\"0\" ...></iframe>",`.
* @property {number} ad_id The ad ID of the creative, as understood by the bidder's system. Used by the line item's [creative in the ad server](http://prebid.org/adops/send-all-bids-adops.html#step-3-add-a-creative).
* @property {string} adUnitCode The code used to uniquely identify the ad unit on the publisher's page.
*
* @property {string} statusMessage The status of the bid. Allowed values: `"Bid available"` or `"Bid returned empty or error response"`.
* @property {number} cpm The exact bid price from the bidder, expressed to the thousandths place. Example: `"0.849"`.
*
* @property {Object} adserverTargeting An object whose values represent the ad server's targeting on the bid.
* @property {string} adserverTargeting.hb_adid The ad ID of the creative, as understood by the ad server.
* @property {string} adserverTargeting.hb_pb The price paid to show the creative, as logged in the ad server.
* @property {string} adserverTargeting.hb_bidder The winning bidder whose ad creative will be served by the ad server.
*/
/**
* Get all of the bids that have been rendered. Useful for [troubleshooting your integration](http://prebid.org/dev-docs/prebid-troubleshooting-guide.html).
* @return {Array<AdapterBidResponse>} A list of bids that have been rendered.
*/
$$PREBID_GLOBAL$$.getAllWinningBids = function () {
return auctionManager.getAllWinningBids();
};
/**
* Get all of the bids that have won their respective auctions.
* @return {Array<AdapterBidResponse>} A list of bids that have won their respective auctions.
*/
$$PREBID_GLOBAL$$.getAllPrebidWinningBids = function () {
return auctionManager.getBidsReceived()
.filter(bid => bid.status === CONSTANTS.BID_STATUS.BID_TARGETING_SET);
};
/**
* Get array of highest cpm bids for all adUnits, or highest cpm bid
* object for the given adUnit
* @param {string} adUnitCode - optional ad unit code
* @alias module:pbjs.getHighestCpmBids
* @return {Array} array containing highest cpm bid object(s)
*/
$$PREBID_GLOBAL$$.getHighestCpmBids = function (adUnitCode) {
return targeting.getWinningBids(adUnitCode);
};
/**
* Mark the winning bid as used, should only be used in conjunction with video
* @typedef {Object} MarkBidRequest
* @property {string} adUnitCode The ad unit code
* @property {string} adId The id representing the ad we want to mark
*
* @alias module:pbjs.markWinningBidAsUsed
*/
$$PREBID_GLOBAL$$.markWinningBidAsUsed = function (markBidRequest) {
let bids = [];
if (markBidRequest.adUnitCode && markBidRequest.adId) {
bids = auctionManager.getBidsReceived()
.filter(bid => bid.adId === markBidRequest.adId && bid.adUnitCode === markBidRequest.adUnitCode);
} else if (markBidRequest.adUnitCode) {
bids = targeting.getWinningBids(markBidRequest.adUnitCode);
} else if (markBidRequest.adId) {
bids = auctionManager.getBidsReceived().filter(bid => bid.adId === markBidRequest.adId);
} else {
logWarn('Improper use of markWinningBidAsUsed. It needs an adUnitCode or an adId to function.');
}
if (bids.length > 0) {
bids[0].status = CONSTANTS.BID_STATUS.RENDERED;
}
};
/**
* Get Prebid config options
* @param {Object} options
* @alias module:pbjs.getConfig
*/
$$PREBID_GLOBAL$$.getConfig = config.getAnyConfig;
$$PREBID_GLOBAL$$.readConfig = config.readAnyConfig;
$$PREBID_GLOBAL$$.mergeConfig = config.mergeConfig;
$$PREBID_GLOBAL$$.mergeBidderConfig = config.mergeBidderConfig;
/**
* Set Prebid config options.
* See https://docs.prebid.org/dev-docs/publisher-api-reference/setConfig.html
*
* @param {Object} options Global Prebid configuration object. Must be JSON - no JavaScript functions are allowed.
*/
$$PREBID_GLOBAL$$.setConfig = config.setConfig;
$$PREBID_GLOBAL$$.setBidderConfig = config.setBidderConfig;
$$PREBID_GLOBAL$$.que.push(() => listenMessagesFromCreative());
/**
* This queue lets users load Prebid asynchronously, but run functions the same way regardless of whether it gets loaded
* before or after their script executes. For example, given the code:
*
* <script src="url/to/Prebid.js" async></script>
* <script>
* var pbjs = pbjs || {};
* pbjs.cmd = pbjs.cmd || [];
* pbjs.cmd.push(functionToExecuteOncePrebidLoads);
* </script>
*
* If the page's script runs before prebid loads, then their function gets added to the queue, and executed
* by prebid once it's done loading. If it runs after prebid loads, then this monkey-patch causes their
* function to execute immediately.
*
* @memberof pbjs
* @param {function} command A function which takes no arguments. This is guaranteed to run exactly once, and only after
* the Prebid script has been fully loaded.
* @alias module:pbjs.cmd.push
*/
$$PREBID_GLOBAL$$.cmd.push = function (command) {
if (typeof command === 'function') {
try {
command.call();
} catch (e) {
logError('Error processing command :', e.message, e.stack);
}
} else {
logError('Commands written into $$PREBID_GLOBAL$$.cmd.push must be wrapped in a function');