-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.js
1214 lines (1088 loc) · 42.5 KB
/
index.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 Adapter from '../../src/adapter.js';
import { createBid } from '../../src/bidfactory.js';
import {
getPrebidInternal, logError, isStr, isPlainObject, logWarn, generateUUID, bind, logMessage,
triggerPixel, insertUserSyncIframe, deepAccess, mergeDeep, deepSetValue, cleanObj, parseSizesInput,
getBidRequest, getDefinedParams, createTrackPixelHtml, pick, deepClone, uniques, flatten, isNumber,
isEmpty, isArray, logInfo, timestamp
} from '../../src/utils.js';
import CONSTANTS from '../../src/constants.json';
import adapterManager from '../../src/adapterManager.js';
import { config } from '../../src/config.js';
import { VIDEO, NATIVE } from '../../src/mediaTypes.js';
import { isValid } from '../../src/adapters/bidderFactory.js';
import events from '../../src/events.js';
import includes from 'core-js-pure/features/array/includes.js';
import { S2S_VENDORS } from './config.js';
import { ajax } from '../../src/ajax.js';
import find from 'core-js-pure/features/array/find.js';
import {hook} from '../../src/hook.js';
const getConfig = config.getConfig;
const TYPE = CONSTANTS.S2S.SRC;
let _syncCount = 0;
const DEFAULT_S2S_TTL = 60;
const DEFAULT_S2S_CURRENCY = 'USD';
const DEFAULT_S2S_NETREVENUE = true;
let _s2sConfigs;
let eidPermissions;
/**
* @typedef {Object} AdapterOptions
* @summary s2sConfig parameter that adds arguments to resulting OpenRTB payload that goes to Prebid Server
* @property {string} adapter
* @property {boolean} enabled
* @property {string} endpoint
* @property {string} syncEndpoint
* @property {number} timeout
* @example
* // example of multiple bidder configuration
* pbjs.setConfig({
* s2sConfig: {
* adapterOptions: {
* rubicon: {singleRequest: false}
* appnexus: {key: "value"}
* }
* }
* });
*/
/**
* @typedef {Object} S2SDefaultConfig
* @summary Base config properties for server to server header bidding
* @property {string} [adapter='prebidServer'] adapter code to use for S2S
* @property {boolean} [allowUnknownBidderCodes=false] allow bids from bidders that were not explicitly requested
* @property {boolean} [enabled=false] enables S2S bidding
* @property {number} [timeout=1000] timeout for S2S bidders - should be lower than `pbjs.requestBids({timeout})`
* @property {number} [syncTimeout=1000] timeout for cookie sync iframe / image rendering
* @property {number} [maxBids=1]
* @property {AdapterOptions} [adapterOptions] adds arguments to resulting OpenRTB payload to Prebid Server
* @property {Object} [syncUrlModifier]
*/
/**
* @typedef {S2SDefaultConfig} S2SConfig
* @summary Configuration for server to server header bidding
* @property {string[]} bidders bidders to request S2S
* @property {string} endpoint endpoint to contact
* @property {string} [defaultVendor] used as key to select the bidder's default config from ßprebidServer/config.js
* @property {boolean} [cacheMarkup] whether to cache the adm result
* @property {string} [syncEndpoint] endpoint URL for syncing cookies
* @property {Object} [extPrebid] properties will be merged into request.ext.prebid
*/
/**
* @type {S2SDefaultConfig}
*/
const s2sDefaultConfig = {
timeout: 1000,
syncTimeout: 1000,
maxBids: 1,
adapter: 'prebidServer',
allowUnknownBidderCodes: false,
adapterOptions: {},
syncUrlModifier: {}
};
config.setDefaults({
's2sConfig': s2sDefaultConfig
});
/**
* @param {S2SConfig} option
* @return {boolean}
*/
function updateConfigDefaultVendor(option) {
if (option.defaultVendor) {
let vendor = option.defaultVendor;
let optionKeys = Object.keys(option);
if (S2S_VENDORS[vendor]) {
// vendor keys will be set if either: the key was not specified by user
// or if the user did not set their own distinct value (ie using the system default) to override the vendor
Object.keys(S2S_VENDORS[vendor]).forEach((vendorKey) => {
if (s2sDefaultConfig[vendorKey] === option[vendorKey] || !includes(optionKeys, vendorKey)) {
option[vendorKey] = S2S_VENDORS[vendor][vendorKey];
}
});
} else {
logError('Incorrect or unavailable prebid server default vendor option: ' + vendor);
return false;
}
}
// this is how we can know if user / defaultVendor has set it, or if we should default to false
return option.enabled = typeof option.enabled === 'boolean' ? option.enabled : false;
}
/**
* @param {S2SConfig} option
* @return {boolean}
*/
function validateConfigRequiredProps(option) {
const keys = Object.keys(option);
if (['accountId', 'bidders', 'endpoint'].filter(key => {
if (!includes(keys, key)) {
logError(key + ' missing in server to server config');
return true;
}
return false;
}).length > 0) {
return false;
}
}
// temporary change to modify the s2sConfig for new format used for endpoint URLs;
// could be removed later as part of a major release, if we decide to not support the old format
function formatUrlParams(option) {
['endpoint', 'syncEndpoint'].forEach((prop) => {
if (isStr(option[prop])) {
let temp = option[prop];
option[prop] = { p1Consent: temp, noP1Consent: temp };
}
if (isPlainObject(option[prop]) && (!option[prop].p1Consent || !option[prop].noP1Consent)) {
['p1Consent', 'noP1Consent'].forEach((conUrl) => {
if (!option[prop][conUrl]) {
logWarn(`s2sConfig.${prop}.${conUrl} not defined. PBS request will be skipped in some P1 scenarios.`);
}
});
}
});
}
/**
* @param {(S2SConfig[]|S2SConfig)} options
*/
function setS2sConfig(options) {
if (!options) {
return;
}
const normalizedOptions = Array.isArray(options) ? options : [options];
const activeBidders = [];
const optionsValid = normalizedOptions.every((option, i, array) => {
formatUrlParams(options);
const updateSuccess = updateConfigDefaultVendor(option);
if (updateSuccess !== false) {
const valid = validateConfigRequiredProps(option);
if (valid !== false) {
if (Array.isArray(option['bidders'])) {
array[i]['bidders'] = option['bidders'].filter(bidder => {
if (activeBidders.indexOf(bidder) === -1) {
activeBidders.push(bidder);
return true;
}
return false;
});
}
return true;
}
}
logWarn('prebidServer: s2s config is disabled');
return false;
});
if (optionsValid) {
return _s2sConfigs = normalizedOptions;
}
}
getConfig('s2sConfig', ({s2sConfig}) => setS2sConfig(s2sConfig));
/**
* resets the _synced variable back to false, primiarily used for testing purposes
*/
export function resetSyncedStatus() {
_syncCount = 0;
}
/**
* @param {Array} bidderCodes list of bidders to request user syncs for.
*/
function queueSync(bidderCodes, gdprConsent, uspConsent, s2sConfig) {
if (_s2sConfigs.length === _syncCount) {
return;
}
_syncCount++;
const payload = {
uuid: generateUUID(),
bidders: bidderCodes,
account: s2sConfig.accountId
};
let userSyncLimit = s2sConfig.userSyncLimit;
if (isNumber(userSyncLimit) && userSyncLimit > 0) {
payload['limit'] = userSyncLimit;
}
if (gdprConsent) {
payload.gdpr = (gdprConsent.gdprApplies) ? 1 : 0;
// attempt to populate gdpr_consent if we know gdprApplies or it may apply
if (gdprConsent.gdprApplies !== false) {
payload.gdpr_consent = gdprConsent.consentString;
}
}
// US Privacy (CCPA) support
if (uspConsent) {
payload.us_privacy = uspConsent;
}
if (typeof s2sConfig.coopSync === 'boolean') {
payload.coopSync = s2sConfig.coopSync;
}
const jsonPayload = JSON.stringify(payload);
ajax(getMatchingConsentUrl(s2sConfig.syncEndpoint, gdprConsent),
(response) => {
try {
response = JSON.parse(response);
doAllSyncs(response.bidder_status, s2sConfig);
} catch (e) {
logError(e);
}
},
jsonPayload,
{
contentType: 'text/plain',
withCredentials: true
});
}
function doAllSyncs(bidders, s2sConfig) {
if (bidders.length === 0) {
return;
}
// pull the syncs off the list in the order that prebid server sends them
const thisSync = bidders.shift();
// if PBS reports this bidder doesn't have an ID, then call the sync and recurse to the next sync entry
if (thisSync.no_cookie) {
doPreBidderSync(thisSync.usersync.type, thisSync.usersync.url, thisSync.bidder, bind.call(doAllSyncs, null, bidders, s2sConfig), s2sConfig);
} else {
// bidder already has an ID, so just recurse to the next sync entry
doAllSyncs(bidders, s2sConfig);
}
}
/**
* Modify the cookie sync url from prebid server to add new params.
*
* @param {string} type the type of sync, "image", "redirect", "iframe"
* @param {string} url the url to sync
* @param {string} bidder name of bidder doing sync for
* @param {function} done an exit callback; to signify this pixel has either: finished rendering or something went wrong
* @param {S2SConfig} s2sConfig
*/
function doPreBidderSync(type, url, bidder, done, s2sConfig) {
if (s2sConfig.syncUrlModifier && typeof s2sConfig.syncUrlModifier[bidder] === 'function') {
url = s2sConfig.syncUrlModifier[bidder](type, url, bidder);
}
doBidderSync(type, url, bidder, done, s2sConfig.syncTimeout)
}
/**
* Run a cookie sync for the given type, url, and bidder
*
* @param {string} type the type of sync, "image", "redirect", "iframe"
* @param {string} url the url to sync
* @param {string} bidder name of bidder doing sync for
* @param {function} done an exit callback; to signify this pixel has either: finished rendering or something went wrong
* @param {number} timeout: maximum time to wait for rendering in milliseconds
*/
function doBidderSync(type, url, bidder, done, timeout) {
if (!url) {
logError(`No sync url for bidder "${bidder}": ${url}`);
done();
} else if (type === 'image' || type === 'redirect') {
logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`);
triggerPixel(url, done, timeout);
} else if (type === 'iframe') {
logMessage(`Invoking iframe user sync for bidder: "${bidder}"`);
insertUserSyncIframe(url, done, timeout);
} else {
logError(`User sync type "${type}" not supported for bidder: "${bidder}"`);
done();
}
}
/**
* Do client-side syncs for bidders.
*
* @param {Array} bidders a list of bidder names
*/
function doClientSideSyncs(bidders, gdprConsent, uspConsent) {
bidders.forEach(bidder => {
let clientAdapter = adapterManager.getBidAdapter(bidder);
if (clientAdapter && clientAdapter.registerSyncs) {
config.runWithBidder(
bidder,
bind.call(
clientAdapter.registerSyncs,
clientAdapter,
[],
gdprConsent,
uspConsent
)
);
}
});
}
function _appendSiteAppDevice(request, pageUrl, accountId) {
if (!request) return;
// ORTB specifies app OR site
if (typeof config.getConfig('app') === 'object') {
request.app = config.getConfig('app');
request.app.publisher = {id: accountId}
} else {
request.site = {};
if (isPlainObject(config.getConfig('site'))) {
request.site = config.getConfig('site');
}
// set publisher.id if not already defined
if (!deepAccess(request.site, 'publisher.id')) {
deepSetValue(request.site, 'publisher.id', accountId);
}
// set site.page if not already defined
if (!request.site.page) {
request.site.page = pageUrl;
}
}
if (typeof config.getConfig('device') === 'object') {
request.device = config.getConfig('device');
}
if (!request.device) {
request.device = {};
}
if (!request.device.w) {
request.device.w = window.innerWidth;
}
if (!request.device.h) {
request.device.h = window.innerHeight;
}
}
function addBidderFirstPartyDataToRequest(request) {
const bidderConfig = config.getBidderConfig();
const fpdConfigs = Object.keys(bidderConfig).reduce((acc, bidder) => {
const currBidderConfig = bidderConfig[bidder];
if (currBidderConfig.ortb2) {
const ortb2 = mergeDeep({}, currBidderConfig.ortb2);
acc.push({
bidders: [ bidder ],
config: { ortb2 }
});
}
return acc;
}, []);
if (fpdConfigs.length) {
deepSetValue(request, 'ext.prebid.bidderconfig', fpdConfigs);
}
}
// https://iabtechlab.com/wp-content/uploads/2016/07/OpenRTB-Native-Ads-Specification-Final-1.2.pdf#page=40
let nativeDataIdMap = {
sponsoredBy: 1, // sponsored
body: 2, // desc
rating: 3,
likes: 4,
downloads: 5,
price: 6,
salePrice: 7,
phone: 8,
address: 9,
body2: 10, // desc2
cta: 12 // ctatext
};
let nativeDataNames = Object.keys(nativeDataIdMap);
let nativeImgIdMap = {
icon: 1,
image: 3
};
let nativeEventTrackerEventMap = {
impression: 1,
'viewable-mrc50': 2,
'viewable-mrc100': 3,
'viewable-video50': 4,
};
let nativeEventTrackerMethodMap = {
img: 1,
js: 2
};
// enable reverse lookup
[
nativeDataIdMap,
nativeImgIdMap,
nativeEventTrackerEventMap,
nativeEventTrackerMethodMap
].forEach(map => {
Object.keys(map).forEach(key => {
map[map[key]] = key;
});
});
/*
* Protocol spec for OpenRTB endpoint
* e.g., https://<prebid-server-url>/v1/openrtb2/auction
*/
let nativeAssetCache = {}; // store processed native params to preserve
/**
* map wurl to auction id and adId for use in the BID_WON event
*/
let wurlMap = {};
/**
* @param {string} auctionId
* @param {string} adId generated value set to bidObject.adId by bidderFactory Bid()
* @param {string} wurl events.winurl passed from prebidServer as wurl
*/
function addWurl(auctionId, adId, wurl) {
if ([auctionId, adId].every(isStr)) {
wurlMap[`${auctionId}${adId}`] = wurl;
}
}
function getPbsResponseData(bidderRequests, response, pbsName, pbjsName) {
const bidderValues = deepAccess(response, `ext.${pbsName}`);
if (bidderValues) {
Object.keys(bidderValues).forEach(bidder => {
let biddersReq = find(bidderRequests, bidderReq => bidderReq.bidderCode === bidder);
if (biddersReq) {
biddersReq[pbjsName] = bidderValues[bidder];
}
});
}
}
/**
* @param {string} auctionId
* @param {string} adId generated value set to bidObject.adId by bidderFactory Bid()
*/
function removeWurl(auctionId, adId) {
if ([auctionId, adId].every(isStr)) {
wurlMap[`${auctionId}${adId}`] = undefined;
}
}
/**
* @param {string} auctionId
* @param {string} adId generated value set to bidObject.adId by bidderFactory Bid()
* @return {(string|undefined)} events.winurl which was passed as wurl
*/
function getWurl(auctionId, adId) {
if ([auctionId, adId].every(isStr)) {
return wurlMap[`${auctionId}${adId}`];
}
}
/**
* remove all cached wurls
*/
export function resetWurlMap() {
wurlMap = {};
}
function ORTB2(s2sBidRequest, bidderRequests, adUnits, requestedBidders) {
this.s2sBidRequest = s2sBidRequest;
this.bidderRequests = bidderRequests;
this.adUnits = adUnits;
this.s2sConfig = s2sBidRequest.s2sConfig;
this.requestedBidders = requestedBidders;
this.bidIdMap = {};
this.adUnitsByImp = {};
this.impRequested = {};
this.auctionId = bidderRequests.map(br => br.auctionId).reduce((l, r) => (l == null || l === r) && r);
this.requestTimestamp = timestamp();
}
Object.assign(ORTB2.prototype, {
buildRequest() {
const {s2sBidRequest, bidderRequests: bidRequests, adUnits, s2sConfig, requestedBidders} = this;
let imps = [];
let aliases = {};
const firstBidRequest = bidRequests[0];
// transform ad unit into array of OpenRTB impression objects
let impIds = new Set();
adUnits.forEach(adUnit => {
// in case there is a duplicate imp.id, add '-2' suffix to the second imp.id.
// e.g. if there are 2 adUnits (case of twin adUnit codes) with code 'test',
// first imp will have id 'test' and second imp will have id 'test-2'
let impressionId = adUnit.code;
let i = 1;
while (impIds.has(impressionId)) {
i++;
impressionId = `${adUnit.code}-${i}`;
}
impIds.add(impressionId);
this.adUnitsByImp[impressionId] = adUnit;
const nativeParams = adUnit.nativeParams;
let nativeAssets;
if (nativeParams) {
try {
nativeAssets = nativeAssetCache[impressionId] = Object.keys(nativeParams).reduce((assets, type) => {
let params = nativeParams[type];
function newAsset(obj) {
return Object.assign({
required: params.required ? 1 : 0
}, obj ? cleanObj(obj) : {});
}
switch (type) {
case 'image':
case 'icon':
let imgTypeId = nativeImgIdMap[type];
let asset = cleanObj({
type: imgTypeId,
w: deepAccess(params, 'sizes.0'),
h: deepAccess(params, 'sizes.1'),
wmin: deepAccess(params, 'aspect_ratios.0.min_width'),
hmin: deepAccess(params, 'aspect_ratios.0.min_height')
});
if (!((asset.w && asset.h) || (asset.hmin && asset.wmin))) {
throw 'invalid img sizes (must provide sizes or min_height & min_width if using aspect_ratios)';
}
if (Array.isArray(params.aspect_ratios)) {
// pass aspect_ratios as ext data I guess?
const aspectRatios = params.aspect_ratios
.filter((ar) => ar.ratio_width && ar.ratio_height)
.map(ratio => `${ratio.ratio_width}:${ratio.ratio_height}`);
if (aspectRatios.length > 0) {
asset.ext = {
aspectratios: aspectRatios
}
}
}
assets.push(newAsset({
img: asset
}));
break;
case 'title':
if (!params.len) {
throw 'invalid title.len';
}
assets.push(newAsset({
title: {
len: params.len
}
}));
break;
default:
let dataAssetTypeId = nativeDataIdMap[type];
if (dataAssetTypeId) {
assets.push(newAsset({
data: {
type: dataAssetTypeId,
len: params.len
}
}))
}
}
return assets;
}, []);
} catch (e) {
logError('error creating native request: ' + String(e))
}
}
const videoParams = deepAccess(adUnit, 'mediaTypes.video');
const bannerParams = deepAccess(adUnit, 'mediaTypes.banner');
adUnit.bids.forEach(bid => {
this.setBidRequestId(impressionId, bid.bidder, bid.bid_id);
// check for and store valid aliases to add to the request
if (adapterManager.aliasRegistry[bid.bidder]) {
const bidder = adapterManager.bidderRegistry[bid.bidder];
// adding alias only if alias source bidder exists and alias isn't configured to be standalone
// pbs adapter
if (bidder && !bidder.getSpec().skipPbsAliasing) {
aliases[bid.bidder] = adapterManager.aliasRegistry[bid.bidder];
}
}
});
let mediaTypes = {};
if (bannerParams && bannerParams.sizes) {
const sizes = parseSizesInput(bannerParams.sizes);
// get banner sizes in form [{ w: <int>, h: <int> }, ...]
const format = sizes.map(size => {
const [ width, height ] = size.split('x');
const w = parseInt(width, 10);
const h = parseInt(height, 10);
return { w, h };
});
mediaTypes['banner'] = {format};
if (bannerParams.pos) mediaTypes['banner'].pos = bannerParams.pos;
}
if (!isEmpty(videoParams)) {
if (videoParams.context === 'outstream' && !videoParams.renderer && !adUnit.renderer) {
// Don't push oustream w/o renderer to request object.
logError('Outstream bid without renderer cannot be sent to Prebid Server.');
} else {
if (videoParams.context === 'instream' && !videoParams.hasOwnProperty('placement')) {
videoParams.placement = 1;
}
mediaTypes['video'] = Object.keys(videoParams).filter(param => param !== 'context')
.reduce((result, param) => {
if (param === 'playerSize') {
result.w = deepAccess(videoParams, `${param}.0.0`);
result.h = deepAccess(videoParams, `${param}.0.1`);
} else {
result[param] = videoParams[param];
}
return result;
}, {});
}
}
if (nativeAssets) {
try {
mediaTypes['native'] = {
request: JSON.stringify({
// TODO: determine best way to pass these and if we allow defaults
context: 1,
plcmttype: 1,
eventtrackers: [
{event: 1, methods: [1]}
],
// TODO: figure out how to support privacy field
// privacy: int
assets: nativeAssets
}),
ver: '1.2'
}
} catch (e) {
logError('error creating native request: ' + String(e))
}
}
// get bidder params in form { <bidder code>: {...params} }
// initialize reduce function with the user defined `ext` properties on the ad unit
const ext = adUnit.bids.reduce((acc, bid) => {
const adapter = adapterManager.bidderRegistry[bid.bidder];
if (adapter && adapter.getSpec().transformBidParams) {
bid.params = adapter.getSpec().transformBidParams(bid.params, true, adUnit, bidRequests);
}
acc[bid.bidder] = (s2sConfig.adapterOptions && s2sConfig.adapterOptions[bid.bidder]) ? Object.assign({}, bid.params, s2sConfig.adapterOptions[bid.bidder]) : bid.params;
return acc;
}, {...deepAccess(adUnit, 'ortb2Imp.ext')});
const imp = { id: impressionId, ext, secure: s2sConfig.secure };
const ortb2 = {...deepAccess(adUnit, 'ortb2Imp.ext.data')};
Object.keys(ortb2).forEach(prop => {
/**
* Prebid AdSlot
* @type {(string|undefined)}
*/
if (prop === 'pbadslot') {
if (typeof ortb2[prop] === 'string' && ortb2[prop]) {
deepSetValue(imp, 'ext.data.pbadslot', ortb2[prop]);
} else {
// remove pbadslot property if it doesn't meet the spec
delete imp.ext.data.pbadslot;
}
} else if (prop === 'adserver') {
/**
* Copy GAM AdUnit and Name to imp
*/
['name', 'adslot'].forEach(name => {
/** @type {(string|undefined)} */
const value = deepAccess(ortb2, `adserver.${name}`);
if (typeof value === 'string' && value) {
deepSetValue(imp, `ext.data.adserver.${name.toLowerCase()}`, value);
}
});
} else {
deepSetValue(imp, `ext.data.${prop}`, ortb2[prop]);
}
});
Object.assign(imp, mediaTypes);
// if storedAuctionResponse has been set, pass SRID
const storedAuctionResponseBid = find(firstBidRequest.bids, bid => (bid.adUnitCode === adUnit.code && bid.storedAuctionResponse));
if (storedAuctionResponseBid) {
deepSetValue(imp, 'ext.prebid.storedauctionresponse.id', storedAuctionResponseBid.storedAuctionResponse.toString());
}
const getFloorBid = find(firstBidRequest.bids, bid => bid.adUnitCode === adUnit.code && typeof bid.getFloor === 'function');
if (getFloorBid) {
let floorInfo;
try {
floorInfo = getFloorBid.getFloor({
currency: config.getConfig('currency.adServerCurrency') || DEFAULT_S2S_CURRENCY,
});
} catch (e) {
logError('PBS: getFloor threw an error: ', e);
}
if (floorInfo && floorInfo.currency && !isNaN(parseFloat(floorInfo.floor))) {
imp.bidfloor = parseFloat(floorInfo.floor);
imp.bidfloorcur = floorInfo.currency
}
}
if (imp.banner || imp.video || imp.native) {
imps.push(imp);
}
});
if (!imps.length) {
logError('Request to Prebid Server rejected due to invalid media type(s) in adUnit.');
return;
}
const request = {
id: firstBidRequest.auctionId,
source: {tid: s2sBidRequest.tid},
tmax: s2sConfig.timeout,
imp: imps,
// to do: add setconfig option to pass test = 1
test: 0,
ext: {
prebid: {
// set ext.prebid.auctiontimestamp with the auction timestamp. Data type is long integer.
auctiontimestamp: firstBidRequest.auctionStart,
targeting: {
// includewinners is always true for openrtb
includewinners: true,
// includebidderkeys always false for openrtb
includebidderkeys: false
}
}
}
};
// This is no longer overwritten unless name and version explicitly overwritten by extPrebid (mergeDeep)
request.ext.prebid = Object.assign(request.ext.prebid, {channel: {name: 'pbjs', version: $$PREBID_GLOBAL$$.version}})
// set debug flag if in debug mode
if (getConfig('debug')) {
request.ext.prebid = Object.assign(request.ext.prebid, {debug: true})
}
// s2sConfig video.ext.prebid is passed through openrtb to PBS
if (s2sConfig.extPrebid && typeof s2sConfig.extPrebid === 'object') {
request.ext.prebid = mergeDeep(request.ext.prebid, s2sConfig.extPrebid);
}
/**
* @type {(string[]|string|undefined)} - OpenRTB property 'cur', currencies available for bids
*/
const adServerCur = config.getConfig('currency.adServerCurrency');
if (adServerCur && typeof adServerCur === 'string') {
// if the value is a string, wrap it with an array
request.cur = [adServerCur];
} else if (Array.isArray(adServerCur) && adServerCur.length) {
// if it's an array, get the first element
request.cur = [adServerCur[0]];
}
_appendSiteAppDevice(request, bidRequests[0].refererInfo.referer, s2sConfig.accountId);
// pass schain object if it is present
const schain = deepAccess(bidRequests, '0.bids.0.schain');
if (schain) {
request.source.ext = {
schain: schain
};
}
if (!isEmpty(aliases)) {
request.ext.prebid.aliases = {...request.ext.prebid.aliases, ...aliases};
}
const bidUserIdAsEids = deepAccess(bidRequests, '0.bids.0.userIdAsEids');
if (isArray(bidUserIdAsEids) && bidUserIdAsEids.length > 0) {
deepSetValue(request, 'user.ext.eids', bidUserIdAsEids);
}
if (isArray(eidPermissions) && eidPermissions.length > 0) {
if (requestedBidders && isArray(requestedBidders)) {
eidPermissions.forEach(i => {
if (i.bidders) {
i.bidders = i.bidders.filter(bidder => includes(requestedBidders, bidder))
}
});
}
deepSetValue(request, 'ext.prebid.data.eidpermissions', eidPermissions);
}
const multibid = config.getConfig('multibid');
if (multibid) {
deepSetValue(request, 'ext.prebid.multibid', multibid.reduce((result, i) => {
let obj = {};
Object.keys(i).forEach(key => {
obj[key.toLowerCase()] = i[key];
});
result.push(obj);
return result;
}, []));
}
if (bidRequests) {
if (firstBidRequest.gdprConsent) {
// note - gdprApplies & consentString may be undefined in certain use-cases for consentManagement module
let gdprApplies;
if (typeof firstBidRequest.gdprConsent.gdprApplies === 'boolean') {
gdprApplies = firstBidRequest.gdprConsent.gdprApplies ? 1 : 0;
}
deepSetValue(request, 'regs.ext.gdpr', gdprApplies);
deepSetValue(request, 'user.ext.consent', firstBidRequest.gdprConsent.consentString);
if (firstBidRequest.gdprConsent.addtlConsent && typeof firstBidRequest.gdprConsent.addtlConsent === 'string') {
deepSetValue(request, 'user.ext.ConsentedProvidersSettings.consented_providers', firstBidRequest.gdprConsent.addtlConsent);
}
}
// US Privacy (CCPA) support
if (firstBidRequest.uspConsent) {
deepSetValue(request, 'regs.ext.us_privacy', firstBidRequest.uspConsent);
}
}
if (getConfig('coppa') === true) {
deepSetValue(request, 'regs.coppa', 1);
}
const commonFpd = getConfig('ortb2') || {};
mergeDeep(request, commonFpd);
addBidderFirstPartyDataToRequest(request);
request.imp.forEach((imp) => this.impRequested[imp.id] = imp);
return request;
},
interpretResponse(response) {
const {bidderRequests, s2sConfig} = this;
const bids = [];
[['errors', 'serverErrors'], ['responsetimemillis', 'serverResponseTimeMs']]
.forEach(info => getPbsResponseData(bidderRequests, response, info[0], info[1]))
if (response.seatbid) {
// a seatbid object contains a `bid` array and a `seat` string
response.seatbid.forEach(seatbid => {
(seatbid.bid || []).forEach(bid => {
const bidRequest = this.getBidRequest(bid.impid, seatbid.seat);
if (bidRequest == null && !s2sConfig.allowUnknownBidderCodes) {
logWarn(`PBS adapter received bid from unknown bidder (${seatbid.seat}), but 's2sConfig.allowUnknownBidderCodes' is not set. Ignoring bid.`);
return;
}
const cpm = bid.price;
const status = cpm !== 0 ? CONSTANTS.STATUS.GOOD : CONSTANTS.STATUS.NO_BID;
let bidObject = createBid(status, {
bidder: seatbid.seat,
src: TYPE,
bidId: bidRequest ? (bidRequest.bidId || bidRequest.bid_Id) : null,
transactionId: this.adUnitsByImp[bid.impid].transactionId,
auctionId: this.auctionId,
});
bidObject.requestTimestamp = this.requestTimestamp;
bidObject.cpm = cpm;
// temporarily leaving attaching it to each bidResponse so no breaking change
// BUT: this is a flat map, so it should be only attached to bidderRequest, a the change above does
let serverResponseTimeMs = deepAccess(response, ['ext', 'responsetimemillis', seatbid.seat].join('.'));
if (bidRequest && serverResponseTimeMs) {
bidRequest.serverResponseTimeMs = serverResponseTimeMs;
}
// Look for seatbid[].bid[].ext.prebid.bidid and place it in the bidResponse object for use in analytics adapters as 'pbsBidId'
const bidId = deepAccess(bid, 'ext.prebid.bidid');
if (isStr(bidId)) {
bidObject.pbsBidId = bidId;
}
// store wurl by auctionId and adId so it can be accessed from the BID_WON event handler
if (isStr(deepAccess(bid, 'ext.prebid.events.win'))) {
addWurl(this.auctionId, bidObject.adId, deepAccess(bid, 'ext.prebid.events.win'));
}
let extPrebidTargeting = deepAccess(bid, 'ext.prebid.targeting');
// If ext.prebid.targeting exists, add it as a property value named 'adserverTargeting'
// The removal of hb_winurl and hb_bidid targeting values is temporary
// once we get through the transition, this block will be removed.
if (isPlainObject(extPrebidTargeting)) {
// If wurl exists, remove hb_winurl and hb_bidid targeting attributes
if (isStr(deepAccess(bid, 'ext.prebid.events.win'))) {
extPrebidTargeting = getDefinedParams(extPrebidTargeting, Object.keys(extPrebidTargeting)
.filter(i => (i.indexOf('hb_winurl') === -1 && i.indexOf('hb_bidid') === -1)));
}
bidObject.adserverTargeting = extPrebidTargeting;
}
bidObject.seatBidId = bid.id;
if (deepAccess(bid, 'ext.prebid.type') === VIDEO) {
bidObject.mediaType = VIDEO;
const impReq = this.impRequested[bid.impid];
[bidObject.playerWidth, bidObject.playerHeight] = [impReq.video.w, impReq.video.h];
// try to get cache values from 'response.ext.prebid.cache.js'
// else try 'bid.ext.prebid.targeting' as fallback
if (bid.ext.prebid.cache && typeof bid.ext.prebid.cache.vastXml === 'object' && bid.ext.prebid.cache.vastXml.cacheId && bid.ext.prebid.cache.vastXml.url) {
bidObject.videoCacheKey = bid.ext.prebid.cache.vastXml.cacheId;
bidObject.vastUrl = bid.ext.prebid.cache.vastXml.url;
} else if (extPrebidTargeting && extPrebidTargeting.hb_uuid && extPrebidTargeting.hb_cache_host && extPrebidTargeting.hb_cache_path) {
bidObject.videoCacheKey = extPrebidTargeting.hb_uuid;
// build url using key and cache host
bidObject.vastUrl = `https://${extPrebidTargeting.hb_cache_host}${extPrebidTargeting.hb_cache_path}?uuid=${extPrebidTargeting.hb_uuid}`;
}
if (bid.adm) { bidObject.vastXml = bid.adm; }
if (!bidObject.vastUrl && bid.nurl) { bidObject.vastUrl = bid.nurl; }
} else if (deepAccess(bid, 'ext.prebid.type') === NATIVE) {
bidObject.mediaType = NATIVE;
let adm;
if (typeof bid.adm === 'string') {
adm = bidObject.adm = JSON.parse(bid.adm);
} else {
adm = bidObject.adm = bid.adm;
}
let trackers = {
[nativeEventTrackerMethodMap.img]: adm.imptrackers || [],
[nativeEventTrackerMethodMap.js]: adm.jstracker ? [adm.jstracker] : []
};
if (adm.eventtrackers) {
adm.eventtrackers.forEach(tracker => {
switch (tracker.method) {
case nativeEventTrackerMethodMap.img:
trackers[nativeEventTrackerMethodMap.img].push(tracker.url);
break;
case nativeEventTrackerMethodMap.js:
trackers[nativeEventTrackerMethodMap.js].push(tracker.url);
break;
}
});
}
if (isPlainObject(adm) && Array.isArray(adm.assets)) {
let origAssets = nativeAssetCache[bid.impid];
bidObject.native = cleanObj(adm.assets.reduce((native, asset) => {
let origAsset = origAssets[asset.id];
if (isPlainObject(asset.img)) {
native[origAsset.img.type ? nativeImgIdMap[origAsset.img.type] : 'image'] = pick(
asset.img,
['url', 'w as width', 'h as height']
);
} else if (isPlainObject(asset.title)) {
native['title'] = asset.title.text
} else if (isPlainObject(asset.data)) {
nativeDataNames.forEach(dataType => {
if (nativeDataIdMap[dataType] === origAsset.data.type) {
native[dataType] = asset.data.value;
}
});