-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
utils.js
1260 lines (1124 loc) · 36.4 KB
/
utils.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 {config} from './config.js';
import {klona} from 'klona/json';
import {includes} from './polyfill.js';
import { EVENTS, S2S } from './constants.js';
import {GreedyPromise} from './utils/promise.js';
import {getGlobal} from './prebidGlobal.js';
import { default as deepAccess } from 'dlv/index.js';
export { deepAccess };
export { dset as deepSetValue } from 'dset';
var tStr = 'String';
var tFn = 'Function';
var tNumb = 'Number';
var tObject = 'Object';
var tBoolean = 'Boolean';
var toString = Object.prototype.toString;
let consoleExists = Boolean(window.console);
let consoleLogExists = Boolean(consoleExists && window.console.log);
let consoleInfoExists = Boolean(consoleExists && window.console.info);
let consoleWarnExists = Boolean(consoleExists && window.console.warn);
let consoleErrorExists = Boolean(consoleExists && window.console.error);
let eventEmitter;
const pbjsInstance = getGlobal();
export function _setEventEmitter(emitFn) {
// called from events.js - this hoop is to avoid circular imports
eventEmitter = emitFn;
}
function emitEvent(...args) {
if (eventEmitter != null) {
eventEmitter(...args);
}
}
// this allows stubbing of utility functions that are used internally by other utility functions
export const internal = {
checkCookieSupport,
createTrackPixelIframeHtml,
getWindowSelf,
getWindowTop,
canAccessWindowTop,
getWindowLocation,
insertUserSyncIframe,
insertElement,
isFn,
triggerPixel,
logError,
logWarn,
logMessage,
logInfo,
parseQS,
formatQS,
deepEqual
};
let prebidInternal = {};
/**
* Returns object that is used as internal prebid namespace
*/
export function getPrebidInternal() {
return prebidInternal;
}
/* utility method to get incremental integer starting from 1 */
var getIncrementalInteger = (function () {
var count = 0;
return function () {
count++;
return count;
};
})();
// generate a random string (to be used as a dynamic JSONP callback)
export function getUniqueIdentifierStr() {
return getIncrementalInteger() + Math.random().toString(16).substr(2);
}
/**
* Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
* where each x is replaced with a random hexadecimal digit from 0 to f,
* and y is replaced with a random hexadecimal digit from 8 to b.
* https://gist.github.com/jed/982883 via node-uuid
*/
export function generateUUID(placeholder) {
return placeholder
? (placeholder ^ _getRandomData() >> placeholder / 4).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateUUID);
}
/**
* Returns random data using the Crypto API if available and Math.random if not
* Method is from https://gist.github.com/jed/982883 like generateUUID, direct link https://gist.github.com/jed/982883#gistcomment-45104
*/
function _getRandomData() {
if (window && window.crypto && window.crypto.getRandomValues) {
return crypto.getRandomValues(new Uint8Array(1))[0] % 16;
} else {
return Math.random() * 16;
}
}
export function getBidIdParameter(key, paramsObj) {
return paramsObj?.[key] || '';
}
// parse a query string object passed in bid params
// bid params should be an object such as {key: "value", key1 : "value1"}
// aliases to formatQS
export function parseQueryStringParameters(queryObj) {
let result = '';
for (var k in queryObj) {
if (queryObj.hasOwnProperty(k)) { result += k + '=' + encodeURIComponent(queryObj[k]) + '&'; }
}
result = result.replace(/&$/, '');
return result;
}
// transform an AdServer targeting bids into a query string to send to the adserver
export function transformAdServerTargetingObj(targeting) {
// we expect to receive targeting for a single slot at a time
if (targeting && Object.getOwnPropertyNames(targeting).length > 0) {
return Object.keys(targeting)
.map(key => `${key}=${encodeURIComponent(targeting[key])}`).join('&');
} else {
return '';
}
}
/**
* Parse a GPT-Style general size Array like `[[300, 250]]` or `"300x250,970x90"` into an array of width, height tuples `[[300, 250]]` or '[[300,250], [970,90]]'
*/
export function sizesToSizeTuples(sizes) {
if (typeof sizes === 'string') {
// multiple sizes will be comma-separated
return sizes
.split(/\s*,\s*/)
.map(sz => sz.match(/^(\d+)x(\d+)$/i))
.filter(match => match)
.map(([_, w, h]) => [parseInt(w, 10), parseInt(h, 10)])
} else if (Array.isArray(sizes)) {
if (isValidGPTSingleSize(sizes)) {
return [sizes]
}
return sizes.filter(isValidGPTSingleSize);
}
return [];
}
/**
* Parse a GPT-Style general size Array like `[[300, 250]]` or `"300x250,970x90"` into an array of sizes `["300x250"]` or '['300x250', '970x90']'
* @param {(Array.<number[]>|Array.<number>)} sizeObj Input array or double array [300,250] or [[300,250], [728,90]]
* @return {Array.<string>} Array of strings like `["300x250"]` or `["300x250", "728x90"]`
*/
export function parseSizesInput(sizeObj) {
return sizesToSizeTuples(sizeObj).map(sizeTupleToSizeString);
}
export function sizeTupleToSizeString(size) {
return size[0] + 'x' + size[1]
}
// Parse a GPT style single size array, (i.e [300, 250])
// into an AppNexus style string, (i.e. 300x250)
export function parseGPTSingleSizeArray(singleSize) {
if (isValidGPTSingleSize(singleSize)) {
return sizeTupleToSizeString(singleSize);
}
}
export function sizeTupleToRtbSize(size) {
return {w: size[0], h: size[1]};
}
// Parse a GPT style single size array, (i.e [300, 250])
// into OpenRTB-compatible (imp.banner.w/h, imp.banner.format.w/h, imp.video.w/h) object(i.e. {w:300, h:250})
export function parseGPTSingleSizeArrayToRtbSize(singleSize) {
if (isValidGPTSingleSize(singleSize)) {
return sizeTupleToRtbSize(singleSize)
}
}
function isValidGPTSingleSize(singleSize) {
// if we aren't exactly 2 items in this array, it is invalid
return isArray(singleSize) && singleSize.length === 2 && (!isNaN(singleSize[0]) && !isNaN(singleSize[1]));
}
export function getWindowTop() {
return window.top;
}
export function getWindowSelf() {
return window.self;
}
export function getWindowLocation() {
return window.location;
}
export function canAccessWindowTop() {
try {
if (internal.getWindowTop().location.href) {
return true;
}
} catch (e) {
return false;
}
}
/**
* Wrappers to console.(log | info | warn | error). Takes N arguments, the same as the native methods
*/
export function logMessage() {
if (debugTurnedOn() && consoleLogExists) {
// eslint-disable-next-line no-console
console.log.apply(console, decorateLog(arguments, 'MESSAGE:'));
}
}
export function logInfo() {
if (debugTurnedOn() && consoleInfoExists) {
// eslint-disable-next-line no-console
console.info.apply(console, decorateLog(arguments, 'INFO:'));
}
}
export function logWarn() {
if (debugTurnedOn() && consoleWarnExists) {
// eslint-disable-next-line no-console
console.warn.apply(console, decorateLog(arguments, 'WARNING:'));
}
emitEvent(EVENTS.AUCTION_DEBUG, { type: 'WARNING', arguments: arguments });
}
export function logError() {
if (debugTurnedOn() && consoleErrorExists) {
// eslint-disable-next-line no-console
console.error.apply(console, decorateLog(arguments, 'ERROR:'));
}
emitEvent(EVENTS.AUCTION_DEBUG, { type: 'ERROR', arguments: arguments });
}
export function prefixLog(prefix) {
function decorate(fn) {
return function (...args) {
fn(prefix, ...args);
}
}
return {
logError: decorate(logError),
logWarn: decorate(logWarn),
logMessage: decorate(logMessage),
logInfo: decorate(logInfo),
}
}
function decorateLog(args, prefix) {
args = [].slice.call(args);
let bidder = config.getCurrentBidder();
prefix && args.unshift(prefix);
if (bidder) {
args.unshift(label('#aaa'));
}
args.unshift(label('#3b88c3'));
args.unshift('%cPrebid' + (bidder ? `%c${bidder}` : ''));
return args;
function label(color) {
return `display: inline-block; color: #fff; background: ${color}; padding: 1px 4px; border-radius: 3px;`
}
}
export function hasConsoleLogger() {
return consoleLogExists;
}
export function debugTurnedOn() {
return !!config.getConfig('debug');
}
export const createIframe = (() => {
const DEFAULTS = {
border: '0px',
hspace: '0',
vspace: '0',
marginWidth: '0',
marginHeight: '0',
scrolling: 'no',
frameBorder: '0',
allowtransparency: 'true'
}
return (doc, attrs, style = {}) => {
const f = doc.createElement('iframe');
Object.assign(f, Object.assign({}, DEFAULTS, attrs));
Object.assign(f.style, style);
return f;
}
})();
export function createInvisibleIframe() {
return createIframe(document, {
id: getUniqueIdentifierStr(),
width: 0,
height: 0,
src: 'about:blank'
}, {
display: 'none',
height: '0px',
width: '0px',
border: '0px'
});
}
/*
* Check if a given parameter name exists in query string
* and if it does return the value
*/
export function getParameterByName(name) {
return parseQS(getWindowLocation().search)[name] || '';
}
/**
* Return if the object is of the
* given type.
* @param {*} object to test
* @param {String} _t type string (e.g., Array)
* @return {Boolean} if object is of type _t
*/
export function isA(object, _t) {
return toString.call(object) === '[object ' + _t + ']';
}
export function isFn(object) {
return isA(object, tFn);
}
export function isStr(object) {
return isA(object, tStr);
}
export const isArray = Array.isArray.bind(Array);
export function isNumber(object) {
return isA(object, tNumb);
}
export function isPlainObject(object) {
return isA(object, tObject);
}
export function isBoolean(object) {
return isA(object, tBoolean);
}
/**
* Return if the object is "empty";
* this includes falsey, no keys, or no items at indices
* @param {*} object object to test
* @return {Boolean} if object is empty
*/
export function isEmpty(object) {
if (!object) return true;
if (isArray(object) || isStr(object)) {
return !(object.length > 0);
}
return Object.keys(object).length <= 0;
}
/**
* Return if string is empty, null, or undefined
* @param str string to test
* @returns {boolean} if string is empty
*/
export function isEmptyStr(str) {
return isStr(str) && (!str || str.length === 0);
}
/**
* Iterate object with the function
* falls back to es5 `forEach`
* @param {Array|Object} object
* @param {Function} fn - The function to execute for each element. It receives three arguments: value, key, and the original object.
* @returns {void}
*/
export function _each(object, fn) {
if (isFn(object?.forEach)) return object.forEach(fn, this);
Object.entries(object || {}).forEach(([k, v]) => fn.call(this, v, k));
}
export function contains(a, obj) {
return isFn(a?.includes) && a.includes(obj);
}
/**
* Map an array or object into another array
* given a function
* @param {Array|Object} object
* @param {Function} callback - The function to execute for each element. It receives three arguments: value, key, and the original object.
* @return {Array}
*/
export function _map(object, callback) {
if (isFn(object?.map)) return object.map(callback);
return Object.entries(object || {}).map(([k, v]) => callback(v, k, object))
}
/*
* Inserts an element(elm) as targets child, by default as first child
* @param {HTMLElement} elm
* @param {HTMLElement} [doc]
* @param {HTMLElement} [target]
* @param {Boolean} [asLastChildChild]
* @return {HTML Element}
*/
export function insertElement(elm, doc, target, asLastChildChild) {
doc = doc || document;
let parentEl;
if (target) {
parentEl = doc.getElementsByTagName(target);
} else {
parentEl = doc.getElementsByTagName('head');
}
try {
parentEl = parentEl.length ? parentEl : doc.getElementsByTagName('body');
if (parentEl.length) {
parentEl = parentEl[0];
let insertBeforeEl = asLastChildChild ? null : parentEl.firstChild;
return parentEl.insertBefore(elm, insertBeforeEl);
}
} catch (e) {}
}
/**
* Returns a promise that completes when the given element triggers a 'load' or 'error' DOM event, or when
* `timeout` milliseconds have elapsed.
*
* @param {HTMLElement} element
* @param {Number} [timeout]
* @returns {Promise}
*/
export function waitForElementToLoad(element, timeout) {
let timer = null;
return new GreedyPromise((resolve) => {
const onLoad = function() {
element.removeEventListener('load', onLoad);
element.removeEventListener('error', onLoad);
if (timer != null) {
window.clearTimeout(timer);
}
resolve();
};
element.addEventListener('load', onLoad);
element.addEventListener('error', onLoad);
if (timeout != null) {
timer = window.setTimeout(onLoad, timeout);
}
});
}
/**
* Inserts an image pixel with the specified `url` for cookie sync
* @param {string} url URL string of the image pixel to load
* @param {function} [done] an optional exit callback, used when this usersync pixel is added during an async process
* @param {Number} [timeout] an optional timeout in milliseconds for the image to load before calling `done`
*/
export function triggerPixel(url, done, timeout) {
const img = new Image();
if (done && internal.isFn(done)) {
waitForElementToLoad(img, timeout).then(done);
}
img.src = url;
}
export function callBurl({ source, burl }) {
if (source === S2S.SRC && burl) {
internal.triggerPixel(burl);
}
}
/**
* Inserts an empty iframe with the specified `html`, primarily used for tracking purposes
* (though could be for other purposes)
* @param {string} htmlCode snippet of HTML code used for tracking purposes
*/
export function insertHtmlIntoIframe(htmlCode) {
if (!htmlCode) {
return;
}
const iframe = createInvisibleIframe();
internal.insertElement(iframe, document, 'body');
((doc) => {
doc.open();
doc.write(htmlCode);
doc.close();
})(iframe.contentWindow.document);
}
/**
* Inserts empty iframe with the specified `url` for cookie sync
* @param {string} url URL to be requested
* @param {function} [done] an optional exit callback, used when this usersync pixel is added during an async process
* @param {Number} [timeout] an optional timeout in milliseconds for the iframe to load before calling `done`
*/
export function insertUserSyncIframe(url, done, timeout) {
let iframeHtml = internal.createTrackPixelIframeHtml(url, false, 'allow-scripts allow-same-origin');
let div = document.createElement('div');
div.innerHTML = iframeHtml;
let iframe = div.firstChild;
if (done && internal.isFn(done)) {
waitForElementToLoad(iframe, timeout).then(done);
}
internal.insertElement(iframe, document, 'html', true);
}
/**
* Creates a snippet of HTML that retrieves the specified `url`
* @param {string} url URL to be requested
* @param encode
* @return {string} HTML snippet that contains the img src = set to `url`
*/
export function createTrackPixelHtml(url, encode = encodeURI) {
if (!url) {
return '';
}
let escapedUrl = encode(url);
let img = '<div style="position:absolute;left:0px;top:0px;visibility:hidden;">';
img += '<img src="' + escapedUrl + '"></div>';
return img;
};
/**
* encodeURI, but preserves macros of the form '${MACRO}' (e.g. '${AUCTION_PRICE}')
* @param url
* @return {string}
*/
export function encodeMacroURI(url) {
const macros = Array.from(url.matchAll(/\$({[^}]+})/g)).map(match => match[1]);
return macros.reduce((str, macro) => {
return str.replace('$' + encodeURIComponent(macro), '$' + macro)
}, encodeURI(url))
}
/**
* Creates a snippet of Iframe HTML that retrieves the specified `url`
* @param {string} url plain URL to be requested
* @param {string} encodeUri boolean if URL should be encoded before inserted. Defaults to true
* @param {string} sandbox string if provided the sandbox attribute will be included with the given value
* @return {string} HTML snippet that contains the iframe src = set to `url`
*/
export function createTrackPixelIframeHtml(url, encodeUri = true, sandbox = '') {
if (!url) {
return '';
}
if (encodeUri) {
url = encodeURI(url);
}
if (sandbox) {
sandbox = `sandbox="${sandbox}"`;
}
return `<iframe ${sandbox} id="${getUniqueIdentifierStr()}"
frameborder="0"
allowtransparency="true"
marginheight="0" marginwidth="0"
width="0" hspace="0" vspace="0" height="0"
style="height:0px;width:0px;display:none;"
scrolling="no"
src="${url}">
</iframe>`;
}
export function uniques(value, index, arry) {
return arry.indexOf(value) === index;
}
export function flatten(a, b) {
return a.concat(b);
}
export function getBidRequest(id, bidderRequests) {
if (!id) {
return;
}
return bidderRequests.flatMap(br => br.bids)
.find(bid => ['bidId', 'adId', 'bid_id'].some(prop => bid[prop] === id))
}
export function getValue(obj, key) {
return obj[key];
}
export function getBidderCodes(adUnits = pbjsInstance.adUnits) {
// this could memoize adUnits
return adUnits.map(unit => unit.bids.map(bid => bid.bidder)
.reduce(flatten, [])).reduce(flatten, []).filter((bidder) => typeof bidder !== 'undefined').filter(uniques);
}
export function isGptPubadsDefined() {
if (window.googletag && isFn(window.googletag.pubads) && isFn(window.googletag.pubads().getSlots)) {
return true;
}
}
export function isApnGetTagDefined() {
if (window.apntag && isFn(window.apntag.getTag)) {
return true;
}
}
/**
* Fisher–Yates shuffle
* http://stackoverflow.com/a/6274398
* https://bost.ocks.org/mike/shuffle/
* istanbul ignore next
*/
export function shuffle(array) {
let counter = array.length;
// while there are elements in the array
while (counter > 0) {
// pick a random index
let index = Math.floor(Math.random() * counter);
// decrease counter by 1
counter--;
// and swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
export function deepClone(obj) {
return klona(obj) || {};
}
export function inIframe() {
try {
return internal.getWindowSelf() !== internal.getWindowTop();
} catch (e) {
return true;
}
}
/**
* https://iabtechlab.com/wp-content/uploads/2016/03/SafeFrames_v1.1_final.pdf
*/
export function isSafeFrameWindow() {
if (!inIframe()) {
return false;
}
const ws = internal.getWindowSelf();
return !!(ws.$sf && ws.$sf.ext);
}
/**
* Returns the result of calling the function $sf.ext.geom() if it exists
* @see https://iabtechlab.com/wp-content/uploads/2016/03/SafeFrames_v1.1_final.pdf — 5.4 Function $sf.ext.geom
* @returns {Object | undefined} geometric information about the container
*/
export function getSafeframeGeometry() {
try {
const ws = getWindowSelf();
return (typeof ws.$sf.ext.geom === 'function') ? ws.$sf.ext.geom() : undefined;
} catch (e) {
logError('Error getting SafeFrame geometry', e);
return undefined;
}
}
export function isSafariBrowser() {
return /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
}
export function replaceMacros(str, subs) {
if (!str) return;
return Object.entries(subs).reduce((str, [key, val]) => {
return str.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), val || '');
}, str);
}
export function replaceAuctionPrice(str, cpm) {
return replaceMacros(str, {AUCTION_PRICE: cpm})
}
export function replaceClickThrough(str, clicktag) {
if (!str || !clicktag || typeof clicktag !== 'string') return;
return str.replace(/\${CLICKTHROUGH}/g, clicktag);
}
export function timestamp() {
return new Date().getTime();
}
/**
* The returned value represents the time elapsed since the time origin. @see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
* @returns {number}
*/
export function getPerformanceNow() {
return (window.performance && window.performance.now && window.performance.now()) || 0;
}
/**
* Retuns the difference between `timing.domLoading` and `timing.navigationStart`.
* This function uses the deprecated `Performance.timing` API and should be removed in future.
* It has not been updated yet because it is still used in some modules.
* @deprecated
* @param {Window} w The window object used to perform the api call. default to window.self
* @returns {number}
*/
export function getDomLoadingDuration(w) {
let domLoadingDuration = -1;
w = w || getWindowSelf();
const performance = w.performance;
if (w.performance?.timing) {
if (w.performance.timing.navigationStart > 0) {
const val = performance.timing.domLoading - performance.timing.navigationStart;
if (val > 0) {
domLoadingDuration = val;
}
}
}
return domLoadingDuration;
}
/**
* When the deviceAccess flag config option is false, no cookies should be read or set
* @returns {boolean}
*/
export function hasDeviceAccess() {
return config.getConfig('deviceAccess') !== false;
}
/**
* @returns {(boolean|undefined)}
*/
export function checkCookieSupport() {
// eslint-disable-next-line prebid/no-member
if (window.navigator.cookieEnabled || !!document.cookie.length) {
return true;
}
}
/**
* Given a function, return a function which only executes the original after
* it's been called numRequiredCalls times.
*
* Note that the arguments from the previous calls will *not* be forwarded to the original function.
* Only the final call's arguments matter.
*
* @param {function} func The function which should be executed, once the returned function has been executed
* numRequiredCalls times.
* @param {number} numRequiredCalls The number of times which the returned function needs to be called before
* func is.
*/
export function delayExecution(func, numRequiredCalls) {
if (numRequiredCalls < 1) {
throw new Error(`numRequiredCalls must be a positive number. Got ${numRequiredCalls}`);
}
let numCalls = 0;
return function () {
numCalls++;
if (numCalls === numRequiredCalls) {
func.apply(this, arguments);
}
}
}
/**
* https://stackoverflow.com/a/34890276/428704
* @param {Array} xs
* @param {string} key
* @returns {Object} {${key_value}: ${groupByArray}, key_value: {groupByArray}}
*/
export function groupBy(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
/**
* Build an object consisting of only defined parameters to avoid creating an
* object with defined keys and undefined values.
* @param {Object} object The object to pick defined params out of
* @param {string[]} params An array of strings representing properties to look for in the object
* @returns {Object} An object containing all the specified values that are defined
*/
export function getDefinedParams(object, params) {
return params
.filter(param => object[param])
.reduce((bid, param) => Object.assign(bid, { [param]: object[param] }), {});
}
/**
* @typedef {Object} MediaTypes
* @property {Object} banner banner configuration
* @property {Object} native native configuration
* @property {Object} video video configuration
*/
/**
* Validates an adunit's `mediaTypes` parameter
* @param {MediaTypes} mediaTypes mediaTypes parameter to validate
* @return {boolean} If object is valid
*/
export function isValidMediaTypes(mediaTypes) {
const SUPPORTED_MEDIA_TYPES = ['banner', 'native', 'video'];
const SUPPORTED_STREAM_TYPES = ['instream', 'outstream', 'adpod'];
const types = Object.keys(mediaTypes);
if (!types.every(type => includes(SUPPORTED_MEDIA_TYPES, type))) {
return false;
}
if (FEATURES.VIDEO && mediaTypes.video && mediaTypes.video.context) {
return includes(SUPPORTED_STREAM_TYPES, mediaTypes.video.context);
}
return true;
}
/**
* Returns user configured bidder params from adunit
* @param {Object} adUnits
* @param {string} adUnitCode code
* @param {string} bidder code
* @return {Array} user configured param for the given bidder adunit configuration
*/
export function getUserConfiguredParams(adUnits, adUnitCode, bidder) {
return adUnits
.filter(adUnit => adUnit.code === adUnitCode)
.flatMap((adUnit) => adUnit.bids)
.filter((bidderData) => bidderData.bidder === bidder)
.map((bidderData) => bidderData.params || {});
}
/**
* Returns Do Not Track state
*/
export function getDNT() {
return navigator.doNotTrack === '1' || window.doNotTrack === '1' || navigator.msDoNotTrack === '1' || navigator.doNotTrack === 'yes';
}
export const compareCodeAndSlot = (slot, adUnitCode) => slot.getAdUnitPath() === adUnitCode || slot.getSlotElementId() === adUnitCode;
/**
* Returns filter function to match adUnitCode in slot
* @param {Object} slot GoogleTag slot
* @return {function} filter function
*/
export function isAdUnitCodeMatchingSlot(slot) {
return (adUnitCode) => compareCodeAndSlot(slot, adUnitCode);
}
/**
* Constructs warning message for when unsupported bidders are dropped from an adunit
* @param {Object} adUnit ad unit from which the bidder is being dropped
* @param {string} bidder bidder code that is not compatible with the adUnit
* @return {string} warning message to display when condition is met
*/
export function unsupportedBidderMessage(adUnit, bidder) {
const mediaType = Object.keys(adUnit.mediaTypes || {'banner': 'banner'}).join(', ');
return `
${adUnit.code} is a ${mediaType} ad unit
containing bidders that don't support ${mediaType}: ${bidder}.
This bidder won't fetch demand.
`;
}
/**
* Checks input is integer or not
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
* @param {*} value
*/
export const isInteger = Number.isInteger.bind(Number);
/**
* Returns a new object with undefined properties removed from given object
* @param obj the object to clean
*/
export function cleanObj(obj) {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => typeof v !== 'undefined'))
}
/**
* Create a new object with selected properties. Also allows property renaming and transform functions.
* @param obj the original object
* @param properties An array of desired properties
*/
export function pick(obj, properties) {
if (typeof obj !== 'object') {
return {};
}
return properties.reduce((newObj, prop, i) => {
if (typeof prop === 'function') {
return newObj;
}
let newProp = prop;
let match = prop.match(/^(.+?)\sas\s(.+?)$/i);
if (match) {
prop = match[1];
newProp = match[2];
}
let value = obj[prop];
if (typeof properties[i + 1] === 'function') {
value = properties[i + 1](value, newObj);
}
if (typeof value !== 'undefined') {
newObj[newProp] = value;
}
return newObj;
}, {});
}
export function isArrayOfNums(val, size) {
return (isArray(val)) && ((size) ? val.length === size : true) && (val.every(v => isInteger(v)));
}
export function parseQS(query) {
return !query ? {} : query
.replace(/^\?/, '')
.split('&')
.reduce((acc, criteria) => {
let [k, v] = criteria.split('=');
if (/\[\]$/.test(k)) {
k = k.replace('[]', '');
acc[k] = acc[k] || [];
acc[k].push(v);
} else {
acc[k] = v || '';
}
return acc;
}, {});
}
export function formatQS(query) {
return Object
.keys(query)
.map(k => Array.isArray(query[k])
? query[k].map(v => `${k}[]=${v}`).join('&')
: `${k}=${query[k]}`)
.join('&');
}
export function parseUrl(url, options) {
let parsed = document.createElement('a');
if (options && 'noDecodeWholeURL' in options && options.noDecodeWholeURL) {
parsed.href = url;
} else {
parsed.href = decodeURIComponent(url);
}
// in window.location 'search' is string, not object
let qsAsString = (options && 'decodeSearchAsString' in options && options.decodeSearchAsString);
return {
href: parsed.href,
protocol: (parsed.protocol || '').replace(/:$/, ''),
hostname: parsed.hostname,
port: +parsed.port,
pathname: parsed.pathname.replace(/^(?!\/)/, '/'),
search: (qsAsString) ? parsed.search : internal.parseQS(parsed.search || ''),
hash: (parsed.hash || '').replace(/^#/, ''),
host: parsed.host || window.location.host
};
}
export function buildUrl(obj) {
return (obj.protocol || 'http') + '://' +
(obj.host ||
obj.hostname + (obj.port ? `:${obj.port}` : '')) +
(obj.pathname || '') +
(obj.search ? `?${internal.formatQS(obj.search || '')}` : '') +
(obj.hash ? `#${obj.hash}` : '');
}
/**
* This function deeply compares two objects checking for their equivalence.
* @param {Object} obj1
* @param {Object} obj2
* @param {Object} [options] - Options for comparison.
* @param {boolean} [options.checkTypes=false] - If set, two objects with identical properties but different constructors will *not* be considered equivalent.