forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathixBidAdapter.js
2082 lines (1842 loc) · 68.4 KB
/
ixBidAdapter.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
import {
contains,
deepAccess,
deepClone,
deepSetValue,
inIframe,
isArray,
isEmpty,
isFn,
isInteger,
isNumber,
isStr,
isPlainObject,
logError,
logWarn,
mergeDeep,
safeJSONParse
} from '../src/utils.js';
import { BANNER, VIDEO, NATIVE } from '../src/mediaTypes.js';
import { config } from '../src/config.js';
import { getStorageManager } from '../src/storageManager.js';
import { find } from '../src/polyfill.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { INSTREAM, OUTSTREAM } from '../src/video.js';
import { Renderer } from '../src/Renderer.js';
import {getGptSlotInfoForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';
const BIDDER_CODE = 'ix';
const GLOBAL_VENDOR_ID = 10;
const SECURE_BID_URL = 'https://htlb.casalemedia.com/openrtb/pbjs';
const SUPPORTED_AD_TYPES = [BANNER, VIDEO, NATIVE];
const BANNER_ENDPOINT_VERSION = 7.2;
const VIDEO_ENDPOINT_VERSION = 8.1;
const CENT_TO_DOLLAR_FACTOR = 100;
const BANNER_TIME_TO_LIVE = 300;
const VIDEO_TIME_TO_LIVE = 3600; // 1hr
const NATIVE_TIME_TO_LIVE = 3600; // Since native can have video, use ttl same as video
const NET_REVENUE = true;
const MAX_REQUEST_LIMIT = 4;
const MAX_EID_SOURCES = 50;
const OUTSTREAM_MINIMUM_PLAYER_SIZE = [144, 144];
const PRICE_TO_DOLLAR_FACTOR = {
JPY: 1
};
const IFRAME_USER_SYNC_URL = 'https://js-sec.indexww.com/um/ixmatch.html';
const FLOOR_SOURCE = { PBJS: 'p', IX: 'x' };
const IMG_USER_SYNC_URL = 'https://dsum.casalemedia.com/pbusermatch?origin=prebid';
const FIRST_PARTY_DATA = {
SITE: [
'id', 'name', 'domain', 'cat', 'sectioncat', 'pagecat', 'page', 'ref', 'search', 'mobile',
'privacypolicy', 'publisher', 'content', 'keywords', 'ext'
],
USER: ['id', 'buyeruid', 'yob', 'gender', 'keywords', 'customdata', 'geo', 'data', 'ext']
};
const SOURCE_RTI_MAPPING = {
'liveramp.com': 'idl',
'netid.de': 'NETID',
'neustar.biz': 'fabrickId',
'zeotap.com': 'zeotapIdPlus',
'uidapi.com': 'UID2',
'adserver.org': 'TDID'
};
const PROVIDERS = [
'lipbid',
'criteoId',
'merkleId',
'parrableId',
'connectid',
'tapadId',
'quantcastId',
'pubProvidedId',
'pairId'
];
const REQUIRED_VIDEO_PARAMS = ['mimes', 'minduration', 'maxduration']; // note: protocol/protocols is also reqd
const VIDEO_PARAMS_ALLOW_LIST = [
'mimes', 'minduration', 'maxduration', 'protocols', 'protocol',
'startdelay', 'placement', 'linearity', 'skip', 'skipmin',
'skipafter', 'sequence', 'battr', 'maxextended', 'minbitrate',
'maxbitrate', 'boxingallowed', 'playbackmethod', 'playbackend',
'delivery', 'pos', 'companionad', 'api', 'companiontype', 'ext',
'playerSize', 'w', 'h', 'plcmt'
];
const LOCAL_STORAGE_KEY = 'ixdiag';
export const LOCAL_STORAGE_FEATURE_TOGGLES_KEY = `${BIDDER_CODE}_features`;
export const storage = getStorageManager({ bidderCode: BIDDER_CODE });
export const FEATURE_TOGGLES = {
// Update with list of CFTs to be requested from Exchange
REQUESTED_FEATURE_TOGGLES: [
'pbjs_enable_multiformat',
'pbjs_allow_all_eids'
],
featureToggles: {},
isFeatureEnabled: function (ft) {
return deepAccess(this.featureToggles, `features.${ft}.activated`, false)
},
getFeatureToggles: function () {
if (storage.localStorageIsEnabled()) {
const parsedToggles = safeJSONParse(storage.getDataFromLocalStorage(LOCAL_STORAGE_FEATURE_TOGGLES_KEY));
if (deepAccess(parsedToggles, 'expiry') && parsedToggles.expiry >= new Date().getTime()) {
this.featureToggles = parsedToggles
} else {
this.clearFeatureToggles();
}
}
},
setFeatureToggles: function (serverResponse) {
const responseBody = serverResponse.body;
const expiryTime = new Date();
const toggles = deepAccess(responseBody, 'ext.features');
if (toggles) {
this.featureToggles = {
expiry: expiryTime.setHours(expiryTime.getHours() + 1),
features: toggles
}
if (storage.localStorageIsEnabled()) {
storage.setDataInLocalStorage(LOCAL_STORAGE_FEATURE_TOGGLES_KEY, JSON.stringify(this.featureToggles));
}
}
},
clearFeatureToggles: function () {
this.featureToggles = {};
if (storage.localStorageIsEnabled()) {
storage.removeDataFromLocalStorage(LOCAL_STORAGE_FEATURE_TOGGLES_KEY);
}
}
};
let siteID = 0;
let gdprConsent = '';
let usPrivacy = '';
let defaultVideoPlacement = false;
// Possible values for bidResponse.seatBid[].bid[].mtype which indicates the type of the creative markup so that it can properly be associated with the right sub-object of the BidRequest.Imp.
const MEDIA_TYPES = {
Banner: 1,
Video: 2,
Audio: 3,
Native: 4
};
/**
* Transform valid bid request config object to banner impression object that will be sent to ad server.
*
* @param {object} bid A valid bid request config object
* @return {object} A impression object that will be sent to ad server.
*/
function bidToBannerImp(bid) {
const imp = bidToImp(bid, BANNER);
imp.banner = {};
imp.adunitCode = bid.adUnitCode;
const impSize = deepAccess(bid, 'params.size');
if (impSize) {
imp.banner.w = impSize[0];
imp.banner.h = impSize[1];
}
imp.banner.topframe = inIframe() ? 0 : 1;
_applyFloor(bid, imp, BANNER);
return imp;
}
/**
* Sets imp.displaymanager
*
* @param {object} imp
* @param {object} bid
*/
function setDisplayManager(imp, bid) {
if (deepAccess(bid, 'mediaTypes.video.context') === OUTSTREAM) {
let renderer = deepAccess(bid, 'mediaTypes.video.renderer');
if (!renderer) {
renderer = deepAccess(bid, 'renderer');
}
if (deepAccess(bid, 'schain', false)) {
imp.displaymanager = 'pbjs_wrapper';
} else if (renderer && typeof (renderer) === 'object') {
if (renderer.url !== undefined) {
let domain = '';
try {
domain = new URL(renderer.url).hostname
} catch {
return;
}
if (domain.includes('js-sec.indexww')) {
imp.displaymanager = 'ix';
} else {
imp.displaymanager = renderer.url;
}
}
} else {
imp.displaymanager = 'ix';
}
}
}
/**
* Transform valid bid request config object to video impression object that will be sent to ad server.
*
* @param {object} bid A valid bid request config object.
* @return {object} A impression object that will be sent to ad server.
*/
export function bidToVideoImp(bid) {
const imp = bidToImp(bid, VIDEO);
const videoAdUnitRef = deepAccess(bid, 'mediaTypes.video');
const videoParamRef = deepAccess(bid, 'params.video');
const videoParamErrors = checkVideoParams(videoAdUnitRef, videoParamRef);
if (videoParamErrors.length) {
return {};
}
imp.video = videoParamRef ? deepClone(bid.params.video) : {};
// populate imp level transactionId
let tid = deepAccess(bid, 'ortb2Imp.ext.tid');
if (tid) {
deepSetValue(imp, 'ext.tid', tid);
}
setDisplayManager(imp, bid);
// AdUnit-Specific First Party Data
addAdUnitFPD(imp, bid);
// copy all video properties to imp object
for (const adUnitProperty in videoAdUnitRef) {
if (VIDEO_PARAMS_ALLOW_LIST.indexOf(adUnitProperty) !== -1 && !imp.video.hasOwnProperty(adUnitProperty)) {
imp.video[adUnitProperty] = videoAdUnitRef[adUnitProperty];
}
}
if (imp.video.minduration > imp.video.maxduration) {
logError(
`IX Bid Adapter: video minduration [${imp.video.minduration}] cannot be greater than video maxduration [${imp.video.maxduration}]`
);
return {};
}
const context = (videoParamRef && videoParamRef.context) || (videoAdUnitRef && videoAdUnitRef.context);
verifyVideoPlcmt(imp);
// if placement not already defined, pick one based on `context`
if (context && !imp.video.hasOwnProperty('placement')) {
if (context === INSTREAM) {
imp.video.placement = 1;
} else if (context === OUTSTREAM) {
if (deepAccess(videoParamRef, 'playerConfig.floatOnScroll')) {
imp.video.placement = 5;
} else {
imp.video.placement = 3;
defaultVideoPlacement = true;
}
} else {
logWarn(`IX Bid Adapter: Video context '${context}' is not supported`);
}
}
if (!(imp.video.w && imp.video.h)) {
// Getting impression Size
const impSize = getFirstSize(deepAccess(imp, 'video.playerSize')) || getFirstSize(deepAccess(bid, 'params.size'));
if (impSize) {
imp.video.w = impSize[0];
imp.video.h = impSize[1];
} else {
logWarn('IX Bid Adapter: Video size is missing in [mediaTypes.video]');
return {};
}
}
_applyFloor(bid, imp, VIDEO);
return imp;
}
function verifyVideoPlcmt(imp) {
if (imp.video.hasOwnProperty('plcmt') && (!isInteger(imp.video.plcmt) || (imp.video.plcmt < 1 || imp.video.plcmt > 4))) {
logWarn(
`IX Bid Adapter: video.plcmt [${imp.video.plcmt}] must be an integer between 1-4 inclusive`
);
delete imp.video.plcmt;
}
}
/**
* Transform valid bid request config object to native impression object that will be sent to ad server.
*
* @param {object} bid A valid bid request config object.
* @return {object} A impression object that will be sent to ad server.
*/
export function bidToNativeImp(bid) {
const imp = bidToImp(bid, NATIVE);
const request = bid.nativeOrtbRequest
request.eventtrackers = [{
event: 1,
methods: [1, 2]
}];
request.privacy = 1;
imp.native = {
request: JSON.stringify(request),
ver: '1.2'
};
// populate imp level transactionId
let tid = deepAccess(bid, 'ortb2Imp.ext.tid');
if (tid) {
deepSetValue(imp, 'ext.tid', tid);
}
// AdUnit-Specific First Party Data
addAdUnitFPD(imp, bid)
_applyFloor(bid, imp, NATIVE);
return imp;
}
/**
* Converts an incoming PBJS bid to an IX Impression
* @param {object} bid PBJS bid object
* @returns {object} IX impression object
*/
function bidToImp(bid, mediaType) {
const imp = {};
imp.id = bid.bidId;
if (isExchangeIdConfigured() && deepAccess(bid, `params.externalId`)) {
deepSetValue(imp, 'ext.externalID', bid.params.externalId);
}
if (deepAccess(bid, `params.${mediaType}.siteId`) && !isNaN(Number(bid.params[mediaType].siteId))) {
switch (mediaType) {
case BANNER:
deepSetValue(imp, 'ext.siteID', bid.params.banner.siteId.toString());
break;
case VIDEO:
deepSetValue(imp, 'ext.siteID', bid.params.video.siteId.toString());
break;
case NATIVE:
deepSetValue(imp, 'ext.siteID', bid.params.native.siteId.toString());
break;
}
} else {
if (bid.params.siteId) {
deepSetValue(imp, 'ext.siteID', bid.params.siteId.toString());
}
}
// populate imp level sid
if (bid.params.hasOwnProperty('id') && (typeof bid.params.id === 'string' || typeof bid.params.id === 'number')) {
deepSetValue(imp, 'ext.sid', String(bid.params.id));
}
return imp;
}
/**
* Gets priceFloors floors and IX adapter floors,
* Validates and sets the higher one on the impression
* @param {object} bid bid object
* @param {object} imp impression object
* @param {string} mediaType the impression ad type, one of the SUPPORTED_AD_TYPES
*/
function _applyFloor(bid, imp, mediaType) {
let adapterFloor = null;
let moduleFloor = null;
if (bid.params.bidFloor && bid.params.bidFloorCur) {
adapterFloor = { floor: bid.params.bidFloor, currency: bid.params.bidFloorCur };
}
if (isFn(bid.getFloor)) {
let _mediaType = '*';
let _size = '*';
if (mediaType && contains(SUPPORTED_AD_TYPES, mediaType)) {
const { w: width, h: height } = imp[mediaType];
_mediaType = mediaType;
_size = [width, height];
}
try {
moduleFloor = bid.getFloor({
mediaType: _mediaType,
size: _size
});
} catch (err) {
// continue with no module floors
logWarn('priceFloors module call getFloor failed, error : ', err);
}
}
// Prioritize module floor over bidder.param floor
let setFloor = false;
if (moduleFloor) {
imp.bidfloor = moduleFloor.floor;
imp.bidfloorcur = moduleFloor.currency;
deepSetValue(imp, 'ext.fl', FLOOR_SOURCE.PBJS);
setFloor = true;
} else if (adapterFloor) {
imp.bidfloor = adapterFloor.floor;
imp.bidfloorcur = adapterFloor.currency;
deepSetValue(imp, 'ext.fl', FLOOR_SOURCE.IX);
setFloor = true;
}
if (setFloor) {
if (mediaType == BANNER) {
deepSetValue(imp, 'banner.ext.bidfloor', imp.bidfloor);
deepSetValue(imp, 'banner.ext.fl', imp.ext.fl);
} else if (mediaType == VIDEO) {
deepSetValue(imp, 'video.ext.bidfloor', imp.bidfloor);
deepSetValue(imp, 'video.ext.fl', imp.ext.fl);
} else {
deepSetValue(imp, 'native.ext.bidfloor', imp.bidfloor);
deepSetValue(imp, 'native.ext.fl', imp.ext.fl);
}
}
}
/**
* Parses a raw bid for the relevant information.
*
* @param {object} rawBid The bid to be parsed.
* @param {string} currency Global currency in bid response.
* @return {object} bid The parsed bid.
*/
function parseBid(rawBid, currency, bidRequest) {
const bid = {};
const isValidExpiry = !!((deepAccess(rawBid, 'exp') && isInteger(rawBid.exp)));
const dealID = deepAccess(rawBid, 'dealid') || deepAccess(rawBid, 'ext.dealid');
if (PRICE_TO_DOLLAR_FACTOR.hasOwnProperty(currency)) {
bid.cpm = rawBid.price / PRICE_TO_DOLLAR_FACTOR[currency];
} else {
bid.cpm = rawBid.price / CENT_TO_DOLLAR_FACTOR;
}
bid.requestId = rawBid.impid;
if (dealID) {
bid.dealId = dealID;
}
bid.netRevenue = NET_REVENUE;
bid.currency = currency;
bid.creativeId = rawBid.hasOwnProperty('crid') ? rawBid.crid : '-';
// If mtype = video is passed and vastURl is not set, set vastxml
if (rawBid.mtype == MEDIA_TYPES.Video && ((rawBid.ext && !rawBid.ext.vasturl) || !rawBid.ext)) {
bid.vastXml = rawBid.adm;
} else if (rawBid.ext && rawBid.ext.vasturl) {
bid.vastUrl = rawBid.ext.vasturl;
}
let parsedAdm = null;
// Detect whether the adm is (probably) JSON
if (typeof rawBid.adm === 'string' && rawBid.adm[0] === '{' && rawBid.adm[rawBid.adm.length - 1] === '}') {
try {
parsedAdm = JSON.parse(rawBid.adm);
} catch (err) {
logWarn('adm looks like JSON but failed to parse: ', err);
}
}
// in the event of a video
if ((rawBid.ext && rawBid.ext.vasturl) || rawBid.mtype == MEDIA_TYPES.Video) {
bid.width = bidRequest.video.w;
bid.height = bidRequest.video.h;
bid.mediaType = VIDEO;
bid.mediaTypes = bidRequest.mediaTypes;
bid.ttl = isValidExpiry ? rawBid.exp : VIDEO_TIME_TO_LIVE;
} else if (parsedAdm && parsedAdm.native) {
bid.native = { ortb: parsedAdm.native };
bid.width = rawBid.w ? rawBid.w : 1;
bid.height = rawBid.h ? rawBid.h : 1;
bid.mediaType = NATIVE;
bid.ttl = isValidExpiry ? rawBid.exp : NATIVE_TIME_TO_LIVE;
} else {
bid.ad = rawBid.adm;
bid.width = rawBid.w;
bid.height = rawBid.h;
bid.mediaType = BANNER;
bid.ttl = isValidExpiry ? rawBid.exp : BANNER_TIME_TO_LIVE;
}
bid.meta = {};
bid.meta.networkId = deepAccess(rawBid, 'ext.dspid');
bid.meta.brandId = deepAccess(rawBid, 'ext.advbrandid');
bid.meta.brandName = deepAccess(rawBid, 'ext.advbrand');
if (rawBid.adomain && rawBid.adomain.length > 0) {
bid.meta.advertiserDomains = rawBid.adomain;
}
if (rawBid.ext?.dsa) {
bid.meta.dsa = rawBid.ext.dsa
}
return bid;
}
/**
* Determines whether or not the given object is valid size format.
*
* @param {*} size The object to be validated.
* @return {boolean} True if this is a valid size format, and false otherwise.
*/
function isValidSize(size) {
return Array.isArray(size) && size.length === 2 && isInteger(size[0]) && isInteger(size[1]);
}
/**
* Determines whether or not the given size object is an element of the size
* array.
*
* @param {Array} sizeArray The size array.
* @param {object} size The size object.
* @return {boolean} True if the size object is an element of the size array, and false
* otherwise.
*/
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;
}
/**
* Checks if all required video params are present
* @param {object} mediaTypeVideoRef Ad unit level mediaTypes object
* @param {object} paramsVideoRef IX bidder params level video object
* @returns {string[]} Are the required video params available
*/
function checkVideoParams(mediaTypeVideoRef, paramsVideoRef) {
const errorList = [];
if (!mediaTypeVideoRef) {
logWarn('IX Bid Adapter: mediaTypes.video is the preferred location for video params in ad unit');
}
for (let property of REQUIRED_VIDEO_PARAMS) {
const propInMediaType = mediaTypeVideoRef && mediaTypeVideoRef.hasOwnProperty(property);
const propInVideoRef = paramsVideoRef && paramsVideoRef.hasOwnProperty(property);
if (!propInMediaType && !propInVideoRef) {
errorList.push(`IX Bid Adapter: ${property} is not included in either the adunit or params level`);
}
}
// check protocols/protocol
const protocolMediaType = mediaTypeVideoRef && mediaTypeVideoRef.hasOwnProperty('protocol');
const protocolsMediaType = mediaTypeVideoRef && mediaTypeVideoRef.hasOwnProperty('protocols');
const protocolVideoRef = paramsVideoRef && paramsVideoRef.hasOwnProperty('protocol');
const protocolsVideoRef = paramsVideoRef && paramsVideoRef.hasOwnProperty('protocols');
if (!(protocolMediaType || protocolsMediaType || protocolVideoRef || protocolsVideoRef)) {
errorList.push('IX Bid Adapter: protocol/protcols is not included in either the adunit or params level');
}
return errorList;
}
/**
* Get One size from Size Array
* [[250,350]] -> [250, 350]
* [250, 350] -> [250, 350]
* @param {Array} sizes array of sizes
*/
function getFirstSize(sizes = []) {
if (isValidSize(sizes)) {
return sizes;
} else if (isValidSize(sizes[0])) {
return sizes[0];
}
return false;
}
/**
* Determines whether or not the given bidFloor parameters are valid.
*
* @param {number} bidFloor The bidFloor parameter inside bid request config.
* @param {number} bidFloorCur The bidFloorCur parameter inside bid request config.
* @return {boolean} True if this is a valid bidFloor parameters format, and false
* otherwise.
*/
function isValidBidFloorParams(bidFloor, bidFloorCur) {
const curRegex = /^[A-Z]{3}$/;
return Boolean(typeof bidFloor === 'number' && typeof bidFloorCur === 'string' &&
bidFloorCur.match(curRegex));
}
function nativeMediaTypeValid(bid) {
const nativeMediaTypes = deepAccess(bid, 'mediaTypes.native');
if (nativeMediaTypes === undefined) {
return true
}
return bid.nativeOrtbRequest && Array.isArray(bid.nativeOrtbRequest.assets) && bid.nativeOrtbRequest.assets.length > 0
}
/**
* Get bid request object with the associated id.
*
* @param {*} id Id of the impression.
* @param {Array} impressions List of impressions sent in the request.
* @return {object} The impression with the associated id.
*/
function getBidRequest(id, impressions, validBidRequests) {
if (!id) {
return;
}
const bidRequest = {
...find(validBidRequests, bid => bid.bidId === id),
...find(impressions, imp => imp.id === id)
}
return bidRequest;
}
/**
* From the userIdAsEids array, filter for the ones our adserver can use, and modify them
* for our purposes, e.g. add rtiPartner
* @param {Array} allEids userIdAsEids passed in by prebid
* @return {object} contains toSend (eids to send to the adserver) and seenSources (used to filter
* identity info from IX Library)
*/
function getEidInfo(allEids) {
let toSend = [];
let seenSources = {};
if (isArray(allEids)) {
for (const eid of allEids) {
const isSourceMapped = SOURCE_RTI_MAPPING.hasOwnProperty(eid.source);
const hasUids = deepAccess(eid, 'uids.0');
if (hasUids) {
seenSources[eid.source] = true;
if (isSourceMapped && SOURCE_RTI_MAPPING[eid.source] !== '') {
eid.uids[0].ext = {
rtiPartner: SOURCE_RTI_MAPPING[eid.source]
};
}
toSend.push(eid);
if (toSend.length >= MAX_EID_SOURCES) {
break;
}
}
}
}
return { toSend, seenSources };
}
/**
* Builds a request object to be sent to the ad server based on bid requests.
*
* @param {Array} validBidRequests A list of valid bid request config objects.
* @param {object} bidderRequest An object containing other info like gdprConsent.
* @param {object} impressions An object containing a list of impression objects describing the bids for each transaction
* @param {Array} version Endpoint version denoting banner, video or native.
* @return {Array} List of objects describing the request to the server.
*
*/
function buildRequest(validBidRequests, bidderRequest, impressions, version) {
// Always use secure HTTPS protocol.
let baseUrl = SECURE_BID_URL;
// Get ids from Prebid User ID Modules
let eidInfo = getEidInfo(deepAccess(validBidRequests, '0.userIdAsEids'));
let userEids = eidInfo.toSend;
// 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') {
addRTI(userEids, eidInfo);
}
const requests = [];
let r = createRequest(validBidRequests);
// Add FTs to be requested from Exchange
r = addRequestedFeatureToggles(r, FEATURE_TOGGLES.REQUESTED_FEATURE_TOGGLES)
// getting ixdiags for adunits of the video, outstream & multi format (MF) style
const fledgeEnabled = deepAccess(bidderRequest, 'paapi.enabled')
let ixdiag = buildIXDiag(validBidRequests, fledgeEnabled);
for (let key in ixdiag) {
r.ext.ixdiag[key] = ixdiag[key];
}
r = enrichRequest(r, bidderRequest, impressions, validBidRequests, userEids);
r = applyRegulations(r, bidderRequest);
let payload = {};
if (validBidRequests[0].params.siteId) {
siteID = validBidRequests[0].params.siteId;
payload.s = siteID;
}
const impKeys = Object.keys(impressions);
let isFpdAdded = false;
for (let adUnitIndex = 0; adUnitIndex < impKeys.length; adUnitIndex++) {
if (requests.length >= MAX_REQUEST_LIMIT) {
break;
}
r = addImpressions(impressions, impKeys, r, adUnitIndex);
const fpd = deepAccess(bidderRequest, 'ortb2') || {};
const site = { ...(fpd.site || fpd.context) };
// update page URL with IX FPD KVs if they exist
site.page = getIxFirstPartyDataPageUrl(bidderRequest);
const user = { ...fpd.user };
if (!isEmpty(fpd) && !isFpdAdded) {
r = addFPD(bidderRequest, r, fpd, site, user);
r.site = mergeDeep({}, r.site, site);
r.user = mergeDeep({}, r.user, user);
isFpdAdded = true;
}
// add identifiers info to ixDiag
r = addIdentifiersInfo(impressions, r, impKeys, adUnitIndex, payload, baseUrl);
const isLastAdUnit = adUnitIndex === impKeys.length - 1;
r = addDeviceInfo(r);
r = deduplicateImpExtFields(r);
r = removeSiteIDs(r);
if (isLastAdUnit) {
let exchangeUrl = `${baseUrl}?`;
if (siteID !== 0) {
exchangeUrl += `s=${siteID}`;
}
if (isExchangeIdConfigured()) {
exchangeUrl += siteID !== 0 ? '&' : '';
exchangeUrl += `p=${config.getConfig('exchangeId')}`;
}
requests.push({
method: 'POST',
url: exchangeUrl,
data: deepClone(r),
option: {
contentType: 'text/plain',
},
validBidRequests
});
r.imp = [];
isFpdAdded = false;
}
}
return requests;
}
/**
* addRTI adds RTI info of the partner to retrieved user IDs from prebid ID module.
*
* @param {Array} userEids userEids info retrieved from prebid
* @param {Array} eidInfo eidInfo info from prebid
*/
function addRTI(userEids, eidInfo) {
let identityInfo = window.headertag.getIdentityInfo();
if (identityInfo && typeof identityInfo === 'object') {
for (const partnerName in identityInfo) {
if (userEids.length >= MAX_EID_SOURCES) {
return
}
if (identityInfo.hasOwnProperty(partnerName)) {
let response = identityInfo[partnerName];
if (!response.responsePending && response.data && typeof response.data === 'object' &&
Object.keys(response.data).length && !eidInfo.seenSources[response.data.source]) {
userEids.push(response.data);
}
}
}
}
}
/**
* createRequest creates the base request object
* @param {Array} validBidRequests A list of valid bid request config objects.
* @return {object} Object describing the request to the server.
*/
function createRequest(validBidRequests) {
const r = {};
// Since bidderRequestId are the same for different bid request, just use the first one.
r.id = validBidRequests[0].bidderRequestId.toString();
r.site = {};
r.ext = {};
r.ext.source = 'prebid';
r.ext.ixdiag = {};
r.ext.ixdiag.ls = storage.localStorageIsEnabled();
r.imp = [];
r.at = 1;
return r
}
/**
* Adds requested feature toggles to the provided request object to be sent to Exchange.
* @param {object} r - The request object to add feature toggles to.
* @param {Array} requestedFeatureToggles - The list of feature toggles to add.
* @returns {object} The updated request object with the added feature toggles.
*/
function addRequestedFeatureToggles(r, requestedFeatureToggles) {
if (requestedFeatureToggles.length > 0) {
r.ext.features = {};
// Loop through each feature toggle and add it to the features object.
// Add current activation status as well.
requestedFeatureToggles.forEach(toggle => {
r.ext.features[toggle] = { activated: FEATURE_TOGGLES.isFeatureEnabled(toggle) };
});
}
return r;
}
/**
* enrichRequest adds userSync configs, source, and referer info to request and ixDiag objects.
*
* @param {object} r Base reuqest object.
* @param {object} bidderRequest An object containing other info like gdprConsent.
* @param {Array} impressions A list of impressions to be added to the request.
* @param {Array} validBidRequests A list of valid bid request config objects.
* @param {Array} userEids User ID info retrieved from Prebid ID module.
* @return {object} Enriched object describing the request to the server.
*/
function enrichRequest(r, bidderRequest, impressions, validBidRequests, userEids) {
const tmax = deepAccess(bidderRequest, 'timeout');
if (tmax) {
r.ext.ixdiag.tmax = tmax;
}
if (config.getConfig('userSync')) {
r.ext.ixdiag.syncsPerBidder = config.getConfig('userSync').syncsPerBidder;
}
// Add number of available imps to ixDiag.
r.ext.ixdiag.imps = Object.keys(impressions).length;
// set source.tid to auctionId for outgoing request to Exchange.
r.source = {
tid: bidderRequest?.ortb2?.source?.tid
}
// if an schain is provided, send it along
if (validBidRequests[0].schain) {
r.source.ext = {};
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;
}
return r
}
/**
* applyRegulations applies regulation info such as GDPR and GPP to the reqeust obejct.
*
* @param {object} r Base reuqest object.
* @param {object} bidderRequest An object containing other info like gdprConsent.
* @return {object} Object enriched with regulation info describing the request to the server.
*/
function applyRegulations(r, bidderRequest) {
// Apply GDPR information to the request if GDPR is enabled.
if (bidderRequest) {
if (bidderRequest.gdprConsent) {
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 (gdprConsent.hasOwnProperty('addtlConsent') && gdprConsent.addtlConsent) {
r.user.ext.consented_providers_settings = {
addtl_consent: gdprConsent.addtlConsent
};
}
}
}
if (bidderRequest.uspConsent) {
deepSetValue(r, 'regs.ext.us_privacy', bidderRequest.uspConsent);
usPrivacy = bidderRequest.uspConsent;
}
const pageUrl = deepAccess(bidderRequest, 'refererInfo.page');
if (pageUrl) {
r.site.page = pageUrl;
}
if (bidderRequest.gppConsent) {
deepSetValue(r, 'regs.gpp', bidderRequest.gppConsent.gppString);
deepSetValue(r, 'regs.gpp_sid', bidderRequest.gppConsent.applicableSections);
}
}
if (config.getConfig('coppa')) {
deepSetValue(r, 'regs.coppa', 1);
}
return r
}
/**
* addImpressions adds impressions to request object
*
* @param {Array} impressions List of impressions to be added to the request.
* @param {Array} impKeys List of impression keys.
* @param {object} r Reuqest object.
* @param {number} adUnitIndex Index of the current add unit
* @return {object} Reqyest object with added impressions describing the request to the server.
*/
function addImpressions(impressions, impKeys, r, adUnitIndex) {
const adUnitImpressions = impressions[impKeys[adUnitIndex]];
const { missingImps: missingBannerImpressions = [], ixImps = [] } = adUnitImpressions;
const sourceImpressions = { ixImps, missingBannerImpressions };
const impressionObjects = Object.keys(sourceImpressions)
.map((key) => sourceImpressions[key])
.filter(item => Array.isArray(item))
.reduce((acc, curr) => acc.concat(...curr), []);
const gpid = impressions[impKeys[adUnitIndex]].gpid;
const dfpAdUnitCode = impressions[impKeys[adUnitIndex]].dfp_ad_unit_code;
const tid = impressions[impKeys[adUnitIndex]].tid;
const sid = impressions[impKeys[adUnitIndex]].sid;
const auctionEnvironment = impressions[impKeys[adUnitIndex]].ae;
const paapi = impressions[impKeys[adUnitIndex]].paapi;
const bannerImpressions = impressionObjects.filter(impression => BANNER in impression);
const otherImpressions = impressionObjects.filter(impression => !(BANNER in impression));
if (bannerImpressions.length > 0) {
const bannerImpsKeyed = bannerImpressions.reduce((acc, bannerImp) => {
if (!acc[bannerImp.adunitCode]) {
acc[bannerImp.adunitCode] = []
}
acc[bannerImp.adunitCode].push(bannerImp);
return acc;
}, {});
for (const impId in bannerImpsKeyed) {
const bannerImps = bannerImpsKeyed[impId];
const { id, banner: { topframe } } = bannerImps[0];
let externalID = deepAccess(bannerImps[0], 'ext.externalID');
const _bannerImpression = {
id,
banner: {
topframe,
format: bannerImps.map(({ banner: { w, h }, ext }) => ({ w, h, ext }))
},
};
for (let i = 0; i < _bannerImpression.banner.format.length; i++) {
// We add sid and externalID in imp.ext therefore, remove from banner.format[].ext
if (_bannerImpression.banner.format[i].ext != null) {
if (_bannerImpression.banner.format[i].ext.sid != null) {
delete _bannerImpression.banner.format[i].ext.sid;
}
if (_bannerImpression.banner.format[i].ext.externalID != null) {
delete _bannerImpression.banner.format[i].ext.externalID;
}
}
// add floor per size
if ('bidfloor' in bannerImps[i]) {
_bannerImpression.banner.format[i].ext.bidfloor = bannerImps[i].bidfloor;
}
if (JSON.stringify(_bannerImpression.banner.format[i].ext) === '{}') {
delete _bannerImpression.banner.format[i].ext;
}
}