-
Notifications
You must be signed in to change notification settings - Fork 216
/
vast-client.js
3868 lines (3668 loc) · 135 KB
/
vast-client.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
function createAd() {
let adAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
id: adAttributes.id || null,
sequence: adAttributes.sequence || null,
adType: adAttributes.adType || null,
adServingId: null,
categories: [],
expires: null,
viewableImpression: [],
system: null,
title: null,
description: null,
advertiser: null,
pricing: null,
survey: null,
// @deprecated in VAST 4.1
errorURLTemplates: [],
impressionURLTemplates: [],
creatives: [],
extensions: [],
adVerifications: [],
blockedAdCategories: [],
followAdditionalWrappers: true,
allowMultipleAds: false,
fallbackOnNoAd: null
};
}
function createAdVerification() {
return {
resource: null,
vendor: null,
browserOptional: false,
apiFramework: null,
type: null,
parameters: null,
trackingEvents: {}
};
}
function createCompanionAd() {
let creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
id: creativeAttributes.id || null,
adType: 'companionAd',
width: creativeAttributes.width || 0,
height: creativeAttributes.height || 0,
assetWidth: creativeAttributes.assetWidth || null,
assetHeight: creativeAttributes.assetHeight || null,
expandedWidth: creativeAttributes.expandedWidth || null,
expandedHeight: creativeAttributes.expandedHeight || null,
apiFramework: creativeAttributes.apiFramework || null,
adSlotId: creativeAttributes.adSlotId || null,
pxratio: creativeAttributes.pxratio || '1',
renderingMode: creativeAttributes.renderingMode || 'default',
staticResources: [],
htmlResources: [],
iframeResources: [],
adParameters: null,
altText: null,
companionClickThroughURLTemplate: null,
companionClickTrackingURLTemplates: [],
trackingEvents: {}
};
}
function isCompanionAd(ad) {
return ad.adType === 'companionAd';
}
function createCreative() {
let creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
id: creativeAttributes.id || null,
adId: creativeAttributes.adId || null,
sequence: creativeAttributes.sequence || null,
apiFramework: creativeAttributes.apiFramework || null,
universalAdIds: [],
creativeExtensions: []
};
}
function createCreativeCompanion() {
let creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
id,
adId,
sequence,
apiFramework
} = createCreative(creativeAttributes);
return {
id,
adId,
sequence,
apiFramework,
type: 'companion',
required: null,
variations: []
};
}
const supportedMacros = ['ADCATEGORIES', 'ADCOUNT', 'ADPLAYHEAD', 'ADSERVINGID', 'ADTYPE', 'APIFRAMEWORKS', 'APPBUNDLE', 'ASSETURI', 'BLOCKEDADCATEGORIES', 'BREAKMAXADLENGTH', 'BREAKMAXADS', 'BREAKMAXDURATION', 'BREAKMINADLENGTH', 'BREAKMINDURATION', 'BREAKPOSITION', 'CLICKPOS', 'CLICKTYPE', 'CLIENTUA', 'CONTENTID', 'CONTENTPLAYHEAD',
// @deprecated VAST 4.1
'CONTENTURI', 'DEVICEIP', 'DEVICEUA', 'DOMAIN', 'EXTENSIONS', 'GDPRCONSENT', 'IFA', 'IFATYPE', 'INVENTORYSTATE', 'LATLONG', 'LIMITADTRACKING', 'MEDIAMIME', 'MEDIAPLAYHEAD', 'OMIDPARTNER', 'PAGEURL', 'PLACEMENTTYPE', 'PLAYERCAPABILITIES', 'PLAYERSIZE', 'PLAYERSTATE', 'PODSEQUENCE', 'REGULATIONS', 'SERVERSIDE', 'SERVERUA', 'TRANSACTIONID', 'UNIVERSALADID', 'VASTVERSIONS', 'VERIFICATIONVENDORS'];
function track(URLTemplates, macros, options) {
const URLs = resolveURLTemplates(URLTemplates, macros, options);
URLs.forEach(URL => {
if (typeof window !== 'undefined' && window !== null) {
const i = new Image();
i.src = URL;
}
});
}
/**
* Replace the provided URLTemplates with the given values
*
* @param {Array} URLTemplates - An array of tracking url templates.
* @param {Object} [macros={}] - An optional Object of parameters to be used in the tracking calls.
* @param {Object} [options={}] - An optional Object of options to be used in the tracking calls.
*/
function resolveURLTemplates(URLTemplates) {
let macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const resolvedURLs = [];
const URLArray = extractURLsFromTemplates(URLTemplates);
// Set default value for invalid ERRORCODE
if (macros['ERRORCODE'] && !options.isCustomCode && !/^[0-9]{3}$/.test(macros['ERRORCODE'])) {
macros['ERRORCODE'] = 900;
}
// Calc random/time based macros
macros['CACHEBUSTING'] = addLeadingZeros(Math.round(Math.random() * 1.0e8));
macros['TIMESTAMP'] = new Date().toISOString();
// RANDOM/random is not defined in VAST 3/4 as a valid macro tho it's used by some adServer (Auditude)
macros['RANDOM'] = macros['random'] = macros['CACHEBUSTING'];
for (const macro in macros) {
macros[macro] = encodeURIComponentRFC3986(macros[macro]);
}
for (const URLTemplateKey in URLArray) {
const resolveURL = URLArray[URLTemplateKey];
if (typeof resolveURL !== 'string') {
continue;
}
resolvedURLs.push(replaceUrlMacros(resolveURL, macros));
}
return resolvedURLs;
}
/**
* Replace the macros tracking url with their value.
* If no value is provided for a supported macro and it exists in the url,
* it will be replaced by -1 as described by the VAST 4.1 iab specifications
*
* @param {String} url - Tracking url.
* @param {Object} macros - Object of macros to be replaced in the tracking calls
*/
function replaceUrlMacros(url, macros) {
url = replaceMacrosValues(url, macros);
// match any macros from the url that was not replaced
const remainingMacros = url.match(/[^[\]]+(?=])/g);
if (!remainingMacros) {
return url;
}
let supportedRemainingMacros = remainingMacros.filter(macro => supportedMacros.indexOf(macro) > -1);
if (supportedRemainingMacros.length === 0) {
return url;
}
supportedRemainingMacros = supportedRemainingMacros.reduce((accumulator, macro) => {
accumulator[macro] = -1;
return accumulator;
}, {});
return replaceMacrosValues(url, supportedRemainingMacros);
}
/**
* Replace the macros tracking url with their value.
*
* @param {String} url - Tracking url.
* @param {Object} macros - Object of macros to be replaced in the tracking calls
*/
function replaceMacrosValues(url, macros) {
let replacedMacrosUrl = url;
for (const key in macros) {
const value = macros[key];
// this will match [${key}] and %%${key}%% and replace it
replacedMacrosUrl = replacedMacrosUrl.replace(new RegExp("(?:\\[|%%)(".concat(key, ")(?:\\]|%%)"), 'g'), value);
}
return replacedMacrosUrl;
}
/**
* Extract the url/s from the URLTemplates.
* If the URLTemplates is an array of urls
* If the URLTemplates object has a url property
* If the URLTemplates is a single string
*
* @param {Array|String} URLTemplates - An array|string of url templates.
*/
function extractURLsFromTemplates(URLTemplates) {
if (Array.isArray(URLTemplates)) {
return URLTemplates.map(URLTemplate => {
return URLTemplate && URLTemplate.hasOwnProperty('url') ? URLTemplate.url : URLTemplate;
});
}
return URLTemplates;
}
/**
* Filter URLTemplates elements .
* To be valid, urls should:
* - have the same protocol as the client
* or
* - be protocol-relative urls
*
* Returns an object with two arrays
* - validUrls : An array of valid URLs
* - invalidUrls: An array of invalid URLs
*
* @param {Array} URLTemplates - A Array of string/object containing urls templates.
* @returns {Object}
*
*/
function filterUrlTemplates(URLTemplates) {
return URLTemplates.reduce((acc, urlTemplate) => {
const url = urlTemplate.url || urlTemplate;
isValidUrl(url) ? acc.validUrls.push(url) : acc.invalidUrls.push(url);
return acc;
}, {
validUrls: [],
invalidUrls: []
});
}
function isValidUrl(url) {
const regex = /^(https?:\/\/|\/\/)/;
return regex.test(url);
}
/**
* Returns a boolean after checking if the object exists in the array.
* true - if the object exists, false otherwise
*
* @param {Object} obj - The object who existence is to be checked.
* @param {Array} list - List of objects.
*/
function containsTemplateObject(obj, list) {
for (let i = 0; i < list.length; i++) {
if (isTemplateObjectEqual(list[i], obj)) {
return true;
}
}
return false;
}
/**
* Returns a boolean after comparing two Template objects.
* true - if the objects are equivalent, false otherwise
*
* @param {Object} obj1
* @param {Object} obj2
*/
function isTemplateObjectEqual(obj1, obj2) {
if (obj1 && obj2) {
const obj1Properties = Object.getOwnPropertyNames(obj1);
const obj2Properties = Object.getOwnPropertyNames(obj2);
// If number of properties is different, objects are not equivalent
if (obj1Properties.length !== obj2Properties.length) {
return false;
}
if (obj1.id !== obj2.id || obj1.url !== obj2.url) {
return false;
}
return true;
}
return false;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
function encodeURIComponentRFC3986(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, c => "%".concat(c.charCodeAt(0).toString(16)));
}
/**
* Return a string of the input number with leading zeros defined by the length param
*
* @param {Number} input - number to convert
* @param {Number} length - length of the desired string
*
* @return {String}
*/
function addLeadingZeros(input) {
let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
return input.toString().padStart(length, '0');
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function flatten(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
/**
* Joins two arrays of objects without duplicates
*
* @param {Array} arr1
* @param {Array} arr2
*
* @return {Array}
*/
function joinArrayOfUniqueTemplateObjs() {
let arr1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let arr2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
const firstArr = Array.isArray(arr1) ? arr1 : [];
const secondArr = Array.isArray(arr2) ? arr2 : [];
const arr = firstArr.concat(secondArr);
return arr.reduce((res, val) => {
if (!containsTemplateObject(val, res)) {
res.push(val);
}
return res;
}, []);
}
/**
* Check if a provided value is a valid time value according to the IAB definition
* Check if a provided value is a valid time value according to the IAB definition: Must be a positive number or -1.
* if not implemented by ad unit or -2 if value is unknown.
* @param {Number} time
*
* @return {Boolean}
*/
function isValidTimeValue(time) {
return Number.isFinite(time) && time >= -2;
}
/**
* Check if we are in a browser environment
* @returns {Boolean}
*/
function isBrowserEnvironment() {
return typeof window !== 'undefined';
}
function formatMacrosValues(macros) {
return typeof macros !== 'object' ? macros : JSON.stringify(macros);
}
const util = {
track,
resolveURLTemplates,
extractURLsFromTemplates,
filterUrlTemplates,
containsTemplateObject,
isTemplateObjectEqual,
encodeURIComponentRFC3986,
replaceUrlMacros,
isNumeric,
flatten,
joinArrayOfUniqueTemplateObjs,
isValidTimeValue,
addLeadingZeros,
isValidUrl,
isBrowserEnvironment,
formatMacrosValues
};
/**
* This module provides support methods to the parsing classes.
*/
/**
* Returns the first element of the given node which nodeName matches the given name.
* @param {Node} node - The node to use to find a match.
* @param {String} name - The name to look for.
* @return {Object|undefined}
*/
function childByName(node, name) {
const childNodes = Array.from(node.childNodes);
return childNodes.find(childNode => childNode.nodeName === name);
}
/**
* Returns all the elements of the given node which nodeName match the given name.
* @param {Node} node - The node to use to find the matches.
* @param {String} name - The name to look for.
* @return {Array}
*/
function childrenByName(node, name) {
const childNodes = Array.from(node.childNodes);
return childNodes.filter(childNode => childNode.nodeName === name);
}
/**
* Converts relative vastAdTagUri.
* @param {String} vastAdTagUrl - The url to resolve.
* @param {String} originalUrl - The original url.
* @return {String}
*/
function resolveVastAdTagURI(vastAdTagUrl, originalUrl) {
if (!originalUrl) {
return vastAdTagUrl;
}
if (vastAdTagUrl.startsWith('//')) {
const {
protocol
} = location;
return "".concat(protocol).concat(vastAdTagUrl);
}
if (!vastAdTagUrl.includes('://')) {
// Resolve relative URLs (mainly for unit testing)
const baseURL = originalUrl.slice(0, originalUrl.lastIndexOf('/'));
return "".concat(baseURL, "/").concat(vastAdTagUrl);
}
return vastAdTagUrl;
}
/**
* Converts a boolean string into a Boolean.
* @param {String} booleanString - The boolean string to convert.
* @return {Boolean}
*/
function parseBoolean(booleanString) {
return ['true', 'TRUE', 'True', '1'].includes(booleanString);
}
/**
* Parses a node text (for legacy support).
* @param {Object} node - The node to parse the text from.
* @return {String}
*/
function parseNodeText(node) {
return node && (node.textContent || node.text || '').trim();
}
/**
* Copies an attribute from a node to another.
* @param {String} attributeName - The name of the attribute to clone.
* @param {Object} nodeSource - The source node to copy the attribute from.
* @param {Object} nodeDestination - The destination node to copy the attribute at.
*/
function copyNodeAttribute(attributeName, nodeSource, nodeDestination) {
const attributeValue = nodeSource.getAttribute(attributeName);
if (attributeValue) {
nodeDestination.setAttribute(attributeName, attributeValue);
}
}
/**
* Converts element attributes into an object, where object key is attribute name
* and object value is attribute value
* @param {Element} element
* @returns {Object}
*/
function parseAttributes(element) {
const nodeAttributes = Array.from(element.attributes);
return nodeAttributes.reduce((acc, nodeAttribute) => {
acc[nodeAttribute.nodeName] = nodeAttribute.nodeValue;
return acc;
}, {});
}
/**
* Parses a String duration into a Number.
* @param {String} durationString - The dureation represented as a string.
* @return {Number}
*/
function parseDuration(durationString) {
if (durationString === null || typeof durationString === 'undefined') {
return -1;
}
// Some VAST doesn't have an HH:MM:SS duration format but instead jus the number of seconds
if (util.isNumeric(durationString)) {
return parseInt(durationString);
}
const durationComponents = durationString.split(':');
if (durationComponents.length !== 3) {
return -1;
}
const secondsAndMS = durationComponents[2].split('.');
let seconds = parseInt(secondsAndMS[0]);
if (secondsAndMS.length === 2) {
seconds += parseFloat("0.".concat(secondsAndMS[1]));
}
const minutes = parseInt(durationComponents[1] * 60);
const hours = parseInt(durationComponents[0] * 60 * 60);
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds) || minutes > 60 * 60 || seconds > 60) {
return -1;
}
return hours + minutes + seconds;
}
/**
* Splits an Array of ads into an Array of Arrays of ads.
* Each subarray contains either one ad or multiple ads (an AdPod)
* @param {Array} ads - An Array of ads to split
* @return {Array}
*/
function splitVAST(ads) {
const splittedVAST = [];
let lastAdPod = null;
ads.forEach((ad, i) => {
if (ad.sequence) {
ad.sequence = parseInt(ad.sequence, 10);
}
// The current Ad may be the next Ad of an AdPod
if (ad.sequence > 1) {
const lastAd = ads[i - 1];
// check if the current Ad is exactly the next one in the AdPod
if (lastAd && lastAd.sequence === ad.sequence - 1) {
lastAdPod && lastAdPod.push(ad);
return;
}
// If the ad had a sequence attribute but it was not part of a correctly formed
// AdPod, let's remove the sequence attribute
delete ad.sequence;
}
lastAdPod = [ad];
splittedVAST.push(lastAdPod);
});
return splittedVAST;
}
/**
* Parses the attributes and assign them to object
* @param {Object} attributes attribute
* @param {Object} verificationObject with properties which can be assigned
*/
function assignAttributes(attributes, verificationObject) {
if (attributes) {
Array.from(attributes).forEach(_ref => {
let {
nodeName,
nodeValue
} = _ref;
if (nodeName && nodeValue && verificationObject.hasOwnProperty(nodeName)) {
let value = nodeValue;
if (typeof verificationObject[nodeName] === 'boolean') {
value = parseBoolean(value);
}
verificationObject[nodeName] = value;
}
});
}
}
/**
* Merges the data between an unwrapped ad and his wrapper.
* @param {Ad} unwrappedAd - The 'unwrapped' Ad.
* @param {Ad} wrapper - The wrapper Ad.
* @return {void}
*/
function mergeWrapperAdData(unwrappedAd, wrapper) {
var _wrapper$creatives;
unwrappedAd.errorURLTemplates = wrapper.errorURLTemplates.concat(unwrappedAd.errorURLTemplates);
unwrappedAd.impressionURLTemplates = wrapper.impressionURLTemplates.concat(unwrappedAd.impressionURLTemplates);
unwrappedAd.extensions = wrapper.extensions.concat(unwrappedAd.extensions);
if (wrapper.viewableImpression.length > 0) {
unwrappedAd.viewableImpression = [...unwrappedAd.viewableImpression, ...wrapper.viewableImpression];
}
// values from the child wrapper will be overridden
unwrappedAd.followAdditionalWrappers = wrapper.followAdditionalWrappers;
unwrappedAd.allowMultipleAds = wrapper.allowMultipleAds;
unwrappedAd.fallbackOnNoAd = wrapper.fallbackOnNoAd;
const wrapperCompanions = (wrapper.creatives || []).filter(creative => creative && creative.type === 'companion');
const wrapperCompanionClickTracking = wrapperCompanions.reduce((result, creative) => {
(creative.variations || []).forEach(variation => {
(variation.companionClickTrackingURLTemplates || []).forEach(companionClickTrackingURLTemplate => {
if (!util.containsTemplateObject(companionClickTrackingURLTemplate, result)) {
result.push(companionClickTrackingURLTemplate);
}
});
});
return result;
}, []);
unwrappedAd.creatives = wrapperCompanions.concat(unwrappedAd.creatives);
const wrapperHasVideoClickTracking = wrapper.videoClickTrackingURLTemplates && wrapper.videoClickTrackingURLTemplates.length;
const wrapperHasVideoCustomClick = wrapper.videoCustomClickURLTemplates && wrapper.videoCustomClickURLTemplates.length;
unwrappedAd.creatives.forEach(creative => {
// merge tracking events
if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) {
for (const eventName in wrapper.trackingEvents[creative.type]) {
const urls = wrapper.trackingEvents[creative.type][eventName];
if (!Array.isArray(creative.trackingEvents[eventName])) {
creative.trackingEvents[eventName] = [];
}
creative.trackingEvents[eventName] = creative.trackingEvents[eventName].concat(urls);
}
}
if (creative.type === 'linear') {
// merge video click tracking url
if (wrapperHasVideoClickTracking) {
creative.videoClickTrackingURLTemplates = creative.videoClickTrackingURLTemplates.concat(wrapper.videoClickTrackingURLTemplates);
}
// merge video custom click url
if (wrapperHasVideoCustomClick) {
creative.videoCustomClickURLTemplates = creative.videoCustomClickURLTemplates.concat(wrapper.videoCustomClickURLTemplates);
}
// VAST 2.0 support - Use Wrapper/linear/clickThrough when Inline/Linear/clickThrough is null
if (wrapper.videoClickThroughURLTemplate && (creative.videoClickThroughURLTemplate === null || typeof creative.videoClickThroughURLTemplate === 'undefined')) {
creative.videoClickThroughURLTemplate = wrapper.videoClickThroughURLTemplate;
}
}
// pass wrapper companion trackers to all companions
if (creative.type === 'companion' && wrapperCompanionClickTracking.length) {
(creative.variations || []).forEach(variation => {
variation.companionClickTrackingURLTemplates = util.joinArrayOfUniqueTemplateObjs(variation.companionClickTrackingURLTemplates, wrapperCompanionClickTracking);
});
}
});
if (wrapper.adVerifications) {
// As specified by VAST specs unwrapped ads should contains wrapper adVerification script
unwrappedAd.adVerifications = unwrappedAd.adVerifications.concat(wrapper.adVerifications);
}
if (wrapper.blockedAdCategories) {
unwrappedAd.blockedAdCategories = unwrappedAd.blockedAdCategories.concat(wrapper.blockedAdCategories);
}
// Merge Wrapper's creatives containing icon elements
if ((_wrapper$creatives = wrapper.creatives) !== null && _wrapper$creatives !== void 0 && _wrapper$creatives.length) {
// As specified by VAST specs, wrapper should not contain any mediafiles
const wrapperCreativesWithIconsNode = wrapper.creatives.filter(creative => {
var _creative$icons;
return ((_creative$icons = creative.icons) === null || _creative$icons === void 0 ? void 0 : _creative$icons.length) && !creative.mediaFiles.length;
});
if (wrapperCreativesWithIconsNode.length) {
unwrappedAd.creatives = unwrappedAd.creatives.concat(wrapperCreativesWithIconsNode);
}
}
}
const parserUtils = {
childByName,
childrenByName,
resolveVastAdTagURI,
parseBoolean,
parseNodeText,
copyNodeAttribute,
parseAttributes,
parseDuration,
splitVAST,
assignAttributes,
mergeWrapperAdData
};
/**
* This module provides methods to parse a VAST CompanionAd Element.
*/
/**
* Parses a CompanionAd.
* @param {Object} creativeElement - The VAST CompanionAd element to parse.
* @param {Object} creativeAttributes - The attributes of the CompanionAd (optional).
* @return {Object} creative - The creative object.
*/
function parseCreativeCompanion(creativeElement, creativeAttributes) {
const creative = createCreativeCompanion(creativeAttributes);
creative.required = creativeElement.getAttribute('required') || null;
creative.variations = parserUtils.childrenByName(creativeElement, 'Companion').map(companionResource => {
const companionAd = createCompanionAd(parserUtils.parseAttributes(companionResource));
companionAd.htmlResources = parserUtils.childrenByName(companionResource, 'HTMLResource').reduce((urls, resource) => {
const url = parserUtils.parseNodeText(resource);
return url ? urls.concat(url) : urls;
}, []);
companionAd.iframeResources = parserUtils.childrenByName(companionResource, 'IFrameResource').reduce((urls, resource) => {
const url = parserUtils.parseNodeText(resource);
return url ? urls.concat(url) : urls;
}, []);
companionAd.staticResources = parserUtils.childrenByName(companionResource, 'StaticResource').reduce((urls, resource) => {
const url = parserUtils.parseNodeText(resource);
return url ? urls.concat({
url,
creativeType: resource.getAttribute('creativeType') || null
}) : urls;
}, []);
companionAd.altText = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'AltText')) || null;
const trackingEventsElement = parserUtils.childByName(companionResource, 'TrackingEvents');
if (trackingEventsElement) {
parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(trackingElement => {
const eventName = trackingElement.getAttribute('event');
const trackingURLTemplate = parserUtils.parseNodeText(trackingElement);
if (eventName && trackingURLTemplate) {
if (!Array.isArray(companionAd.trackingEvents[eventName])) {
companionAd.trackingEvents[eventName] = [];
}
companionAd.trackingEvents[eventName].push(trackingURLTemplate);
}
});
}
companionAd.companionClickTrackingURLTemplates = parserUtils.childrenByName(companionResource, 'CompanionClickTracking').map(clickTrackingElement => {
return {
id: clickTrackingElement.getAttribute('id') || null,
url: parserUtils.parseNodeText(clickTrackingElement)
};
});
companionAd.companionClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'CompanionClickThrough')) || null;
const adParametersElement = parserUtils.childByName(companionResource, 'AdParameters');
if (adParametersElement) {
companionAd.adParameters = {
value: parserUtils.parseNodeText(adParametersElement),
xmlEncoded: adParametersElement.getAttribute('xmlEncoded') || null
};
}
return companionAd;
});
return creative;
}
function createCreativeLinear() {
let creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
id,
adId,
sequence,
apiFramework
} = createCreative(creativeAttributes);
return {
id,
adId,
sequence,
apiFramework,
type: 'linear',
duration: 0,
skipDelay: null,
mediaFiles: [],
mezzanine: null,
interactiveCreativeFile: null,
closedCaptionFiles: [],
videoClickThroughURLTemplate: null,
videoClickTrackingURLTemplates: [],
videoCustomClickURLTemplates: [],
adParameters: null,
icons: [],
trackingEvents: {}
};
}
function isCreativeLinear(ad) {
return ad.type === 'linear';
}
function createClosedCaptionFile() {
let closedCaptionAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
type: closedCaptionAttributes.type || null,
language: closedCaptionAttributes.language || null,
fileURL: null
};
}
function createIcon() {
return {
program: null,
height: 0,
width: 0,
xPosition: 0,
yPosition: 0,
apiFramework: null,
offset: null,
duration: 0,
type: null,
staticResource: null,
htmlResource: null,
iframeResource: null,
pxratio: '1',
iconClickThroughURLTemplate: null,
iconClickTrackingURLTemplates: [],
iconViewTrackingURLTemplate: null,
iconClickFallbackImages: []
};
}
function createInteractiveCreativeFile() {
let interactiveCreativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
type: interactiveCreativeAttributes.type || null,
apiFramework: interactiveCreativeAttributes.apiFramework || null,
variableDuration: parserUtils.parseBoolean(interactiveCreativeAttributes.variableDuration),
fileURL: null
};
}
function createMediaFile() {
return {
id: null,
fileURL: null,
fileSize: 0,
deliveryType: 'progressive',
mimeType: null,
mediaType: null,
codec: null,
bitrate: 0,
minBitrate: 0,
maxBitrate: 0,
width: 0,
height: 0,
apiFramework: null,
// @deprecated in VAST 4.1. <InteractiveCreativeFile> should be used instead.
scalable: null,
maintainAspectRatio: null
};
}
function createMezzanine() {
return {
id: null,
fileURL: null,
delivery: null,
codec: null,
type: null,
width: 0,
height: 0,
fileSize: 0,
mediaType: '2D'
};
}
/**
* This module provides methods to parse a VAST Linear Element.
*/
/**
* Parses a Linear element.
* @param {Object} creativeElement - The VAST Linear element to parse.
* @param {any} creativeAttributes - The attributes of the Linear (optional).
* @return {Object} creative - The creativeLinear object.
*/
function parseCreativeLinear(creativeElement, creativeAttributes) {
let offset;
const creative = createCreativeLinear(creativeAttributes);
creative.duration = parserUtils.parseDuration(parserUtils.parseNodeText(parserUtils.childByName(creativeElement, 'Duration')));
const skipOffset = creativeElement.getAttribute('skipoffset');
if (typeof skipOffset === 'undefined' || skipOffset === null) {
creative.skipDelay = null;
} else if (skipOffset.charAt(skipOffset.length - 1) === '%' && creative.duration !== -1) {
const percent = parseInt(skipOffset, 10);
creative.skipDelay = creative.duration * (percent / 100);
} else {
creative.skipDelay = parserUtils.parseDuration(skipOffset);
}
const videoClicksElement = parserUtils.childByName(creativeElement, 'VideoClicks');
if (videoClicksElement) {
const videoClickThroughElement = parserUtils.childByName(videoClicksElement, 'ClickThrough');
if (videoClickThroughElement) {
creative.videoClickThroughURLTemplate = {
id: videoClickThroughElement.getAttribute('id') || null,
url: parserUtils.parseNodeText(videoClickThroughElement)
};
} else {
creative.videoClickThroughURLTemplate = null;
}
parserUtils.childrenByName(videoClicksElement, 'ClickTracking').forEach(clickTrackingElement => {
creative.videoClickTrackingURLTemplates.push({
id: clickTrackingElement.getAttribute('id') || null,
url: parserUtils.parseNodeText(clickTrackingElement)
});
});
parserUtils.childrenByName(videoClicksElement, 'CustomClick').forEach(customClickElement => {
creative.videoCustomClickURLTemplates.push({
id: customClickElement.getAttribute('id') || null,
url: parserUtils.parseNodeText(customClickElement)
});
});
}
const adParamsElement = parserUtils.childByName(creativeElement, 'AdParameters');
if (adParamsElement) {
creative.adParameters = {
value: parserUtils.parseNodeText(adParamsElement),
xmlEncoded: adParamsElement.getAttribute('xmlEncoded') || null
};
}
parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(trackingEventsElement => {
parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(trackingElement => {
let eventName = trackingElement.getAttribute('event');
const trackingURLTemplate = parserUtils.parseNodeText(trackingElement);
if (eventName && trackingURLTemplate) {
if (eventName === 'progress') {
offset = trackingElement.getAttribute('offset');
if (!offset) {
return;
}
if (offset.charAt(offset.length - 1) === '%') {
eventName = "progress-".concat(offset);
} else {
eventName = "progress-".concat(Math.round(parserUtils.parseDuration(offset)));
}
}
if (!Array.isArray(creative.trackingEvents[eventName])) {
creative.trackingEvents[eventName] = [];
}
creative.trackingEvents[eventName].push(trackingURLTemplate);
}
});
});
parserUtils.childrenByName(creativeElement, 'MediaFiles').forEach(mediaFilesElement => {
parserUtils.childrenByName(mediaFilesElement, 'MediaFile').forEach(mediaFileElement => {
creative.mediaFiles.push(parseMediaFile(mediaFileElement));
});
const interactiveCreativeElement = parserUtils.childByName(mediaFilesElement, 'InteractiveCreativeFile');
if (interactiveCreativeElement) {
creative.interactiveCreativeFile = parseInteractiveCreativeFile(interactiveCreativeElement);
}
const closedCaptionElements = parserUtils.childByName(mediaFilesElement, 'ClosedCaptionFiles');
if (closedCaptionElements) {
parserUtils.childrenByName(closedCaptionElements, 'ClosedCaptionFile').forEach(closedCaptionElement => {
const closedCaptionFile = createClosedCaptionFile(parserUtils.parseAttributes(closedCaptionElement));
closedCaptionFile.fileURL = parserUtils.parseNodeText(closedCaptionElement);
creative.closedCaptionFiles.push(closedCaptionFile);
});
}
const mezzanineElement = parserUtils.childByName(mediaFilesElement, 'Mezzanine');
const requiredAttributes = getRequiredAttributes(mezzanineElement, ['delivery', 'type', 'width', 'height']);
if (requiredAttributes) {
const mezzanine = createMezzanine();
mezzanine.id = mezzanineElement.getAttribute('id');
mezzanine.fileURL = parserUtils.parseNodeText(mezzanineElement);
mezzanine.delivery = requiredAttributes.delivery;
mezzanine.codec = mezzanineElement.getAttribute('codec');
mezzanine.type = requiredAttributes.type;
mezzanine.width = parseInt(requiredAttributes.width, 10);
mezzanine.height = parseInt(requiredAttributes.height, 10);
mezzanine.fileSize = parseInt(mezzanineElement.getAttribute('fileSize'), 10);
mezzanine.mediaType = mezzanineElement.getAttribute('mediaType') || '2D';
creative.mezzanine = mezzanine;
}
});
const iconsElement = parserUtils.childByName(creativeElement, 'Icons');
if (iconsElement) {
parserUtils.childrenByName(iconsElement, 'Icon').forEach(iconElement => {
creative.icons.push(parseIcon(iconElement));
});
}
return creative;
}
/**
* Parses the MediaFile element from VAST.
* @param {Object} mediaFileElement - The VAST MediaFile element.
* @return {Object} - Parsed mediaFile object.
*/
function parseMediaFile(mediaFileElement) {
const mediaFile = createMediaFile();
mediaFile.id = mediaFileElement.getAttribute('id');
mediaFile.fileURL = parserUtils.parseNodeText(mediaFileElement);
mediaFile.deliveryType = mediaFileElement.getAttribute('delivery');
mediaFile.codec = mediaFileElement.getAttribute('codec');
mediaFile.mimeType = mediaFileElement.getAttribute('type');
mediaFile.mediaType = mediaFileElement.getAttribute('mediaType') || '2D';
mediaFile.apiFramework = mediaFileElement.getAttribute('apiFramework');
mediaFile.fileSize = parseInt(mediaFileElement.getAttribute('fileSize') || 0);
mediaFile.bitrate = parseInt(mediaFileElement.getAttribute('bitrate') || 0);
mediaFile.minBitrate = parseInt(mediaFileElement.getAttribute('minBitrate') || 0);
mediaFile.maxBitrate = parseInt(mediaFileElement.getAttribute('maxBitrate') || 0);
mediaFile.width = parseInt(mediaFileElement.getAttribute('width') || 0);
mediaFile.height = parseInt(mediaFileElement.getAttribute('height') || 0);
const scalable = mediaFileElement.getAttribute('scalable');
if (scalable && typeof scalable === 'string') {
mediaFile.scalable = parserUtils.parseBoolean(scalable);
}
const maintainAspectRatio = mediaFileElement.getAttribute('maintainAspectRatio');
if (maintainAspectRatio && typeof maintainAspectRatio === 'string') {
mediaFile.maintainAspectRatio = parserUtils.parseBoolean(maintainAspectRatio);
}
return mediaFile;
}
/**
* Parses the InteractiveCreativeFile element from VAST MediaFiles node.
* @param {Object} interactiveCreativeElement - The VAST InteractiveCreativeFile element.
* @return {Object} - Parsed interactiveCreativeFile object.
*/
function parseInteractiveCreativeFile(interactiveCreativeElement) {
const interactiveCreativeFile = createInteractiveCreativeFile(parserUtils.parseAttributes(interactiveCreativeElement));
interactiveCreativeFile.fileURL = parserUtils.parseNodeText(interactiveCreativeElement);
return interactiveCreativeFile;
}
/**
* Parses the Icon element from VAST.
* @param {Object} iconElement - The VAST Icon element.
* @return {Object} - Parsed icon object.
*/
function parseIcon(iconElement) {
const icon = createIcon();
icon.program = iconElement.getAttribute('program');
icon.height = parseInt(iconElement.getAttribute('height') || 0);
icon.width = parseInt(iconElement.getAttribute('width') || 0);
icon.xPosition = parseXPosition(iconElement.getAttribute('xPosition'));
icon.yPosition = parseYPosition(iconElement.getAttribute('yPosition'));
icon.apiFramework = iconElement.getAttribute('apiFramework');
icon.pxratio = iconElement.getAttribute('pxratio') || '1';
icon.offset = parserUtils.parseDuration(iconElement.getAttribute('offset'));
icon.duration = parserUtils.parseDuration(iconElement.getAttribute('duration'));
parserUtils.childrenByName(iconElement, 'HTMLResource').forEach(htmlElement => {
icon.type = htmlElement.getAttribute('creativeType') || 'text/html';