From a41ef09ed4f62f0ebf23662ead4cbad1637f7ca4 Mon Sep 17 00:00:00 2001 From: zacharieTaifour Date: Wed, 23 Aug 2023 17:50:16 +0200 Subject: [PATCH] Bundle release 5.0.0 --- dist/vast-client-browser.min.js | 2 +- dist/vast-client-node.js | 1213 ++++++++++++------------------- dist/vast-client-node.min.js | 2 +- dist/vast-client.js | 1202 ++++++++++++------------------ dist/vast-client.min.js | 2 +- 5 files changed, 893 insertions(+), 1528 deletions(-) diff --git a/dist/vast-client-browser.min.js b/dist/vast-client-browser.min.js index 49c2ae8a..e0c492a9 100644 --- a/dist/vast-client-browser.min.js +++ b/dist/vast-client-browser.min.js @@ -1 +1 @@ -var VAST=function(e){"use strict";function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(e){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}var m=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 g(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=A(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=E(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=b(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(T(s,t))}return i}function T(e,t){var r=(e=y(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return m.indexOf(e)>-1}));return 0===i.length?e:y(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function y(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function A(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function k(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var N={track:function(e,t,r){g(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:g,extractURLsFromTemplates:A,containsTemplateObject:k,isTemplateObjectEqual:R,encodeURIComponentRFC3986:b,replaceUrlMacros:T,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[],n=r.concat(i);return n.reduce((function(e,t){return k(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:E};function L(e){return-1!==["true","TRUE","True","1"].indexOf(e)}var w={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:L,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i3600||i>60?-1:a+n+i},splitVAST:function(e){var t=[],r=null;return e.forEach((function(i,n){if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=L(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(h(e.viewableImpression),h(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var r=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),i=r.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){N.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=r.concat(e.creatives);var n=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,a=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var o=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(o)}"linear"===e.type&&(n&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),a&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&i.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=N.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,i)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories))}};function U(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=w.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotID:e.adSlotID||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,xmlEncoded:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(w.parseAttributes(e));t.htmlResources=w.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=w.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=w.childrenByName(e,"StaticResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=w.parseNodeText(w.childByName(e,"AltText"))||null;var r=w.childByName(e,"TrackingEvents");r&&w.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=w.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=w.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:w.parseNodeText(e)}})),t.companionClickThroughURLTemplate=w.parseNodeText(w.childByName(e,"CompanionClickThrough"))||null;var i=w.childByName(e,"AdParameters");return i&&(t.adParameters=w.parseNodeText(i),t.xmlEncoded=i.getAttribute("xmlEncoded")||null),t})),r}function C(e){return"linear"===e.type}function I(e,t){var r,i=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=w.parseDuration(w.parseNodeText(w.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=w.parseDuration(n);var o=w.childByName(e,"VideoClicks");if(o){var s=w.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:w.parseNodeText(s)}:null,w.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})),w.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})}))}var l=w.childByName(e,"AdParameters");l&&(i.adParameters=w.parseNodeText(l)),w.childrenByName(e,"TrackingEvents").forEach((function(e){w.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=w.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(w.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),w.childrenByName(e,"MediaFiles").forEach((function(e){w.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=w.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=w.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=w.parseBoolean(i));return t}(e))}));var t=w.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:w.parseBoolean(e.variableDuration),fileURL:null}}(w.parseAttributes(e));return t.fileURL=w.parseNodeText(e),t}(t));var r=w.childByName(e,"ClosedCaptionFiles");r&&w.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(w.parseAttributes(e));t.fileURL=w.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=w.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var c={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};c.id=s.getAttribute("id"),c.fileURL=w.parseNodeText(s),c.delivery=l.delivery,c.codec=s.getAttribute("codec"),c.type=l.type,c.width=parseInt(l.width,10),c.height=parseInt(l.height,10),c.fileSize=parseInt(s.getAttribute("fileSize"),10),c.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=c}}));var c=w.childByName(e,"Icons");return c&&w.childrenByName(c,"Icon").forEach((function(e){i.icons.push(function(e){var t={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};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=w.parseDuration(e.getAttribute("offset")),t.duration=w.parseDuration(e.getAttribute("duration")),w.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=w.parseNodeText(e)})),w.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=w.parseNodeText(e)})),w.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=w.parseNodeText(e)}));var r=w.childByName(e,"IconClicks");r&&(t.iconClickThroughURLTemplate=w.parseNodeText(w.childByName(r,"IconClickThrough")),w.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})));return t.iconViewTrackingURLTemplate=w.parseNodeText(w.childByName(e,"IconViewTracking")),t}(e))})),i}function x(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return w.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;w.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=w.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),w.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=w.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=w.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=w.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),w.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=w.parseNodeText(e)})),w.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=w.parseNodeText(e)})),w.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=w.parseNodeText(e)}));var i=w.childByName(e,"AdParameters");i&&(t.adParameters=w.parseNodeText(i)),t.nonlinearClickThroughURLTemplate=w.parseNodeText(w.childByName(e,"NonLinearClickThrough")),w.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})),r.variations.push(t)})),r}function S(e){var t=[];return e.forEach((function(e){var r=O(e);r&&t.push(r)})),t}function O(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=O(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var c=w.parseNodeText(e);""!==c&&(r.value=c),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function D(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:V(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];w.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:w.parseNodeText(e)};n.push(t)}));var a=w.childByName(e,"CreativeExtensions");for(var o in a&&(r=S(w.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=I(s,i);break;case"NonLinearAds":l=x(s,i);break;case"CompanionAds":l=U(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function V(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var P={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function B(e,t){if(P[e.nodeName]&&P[e.nodeName].attributes){var r=P[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&j({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function F(e,t,r){var i=P[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!w.childByName(e,t)}));a.length>0&&j({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return w.childByName(e,t)}))||j({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function M(e){return e.children&&0!==e.children.length}function j(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var W={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),B(t,r),M(t)){F(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(w.copyNodeAttribute("id",e,s),w.copyNodeAttribute("sequence",e,s),w.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:G(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:H(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function H(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds;return!1===i&&e.getAttribute("sequence")?null:_(e,t)}function _(e,t){var r=[];t&&W.verifyRequiredValues(e,t);var i=e.childNodes,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(w.parseAttributes(e));for(var a in i){var o=i[a];switch(o.nodeName){case"Error":n.errorURLTemplates.push(w.parseNodeText(o));break;case"Impression":n.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:w.parseNodeText(o)});break;case"Creatives":n.creatives=D(w.childrenByName(o,"Creative"));break;case"Extensions":var s=w.childrenByName(o,"Extension");n.extensions=S(s),n.adVerifications.length||(r=Y(s));break;case"AdVerifications":n.adVerifications=z(w.childrenByName(o,"Verification"));break;case"AdSystem":n.system={value:w.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":n.title=w.parseNodeText(o);break;case"AdServingId":n.adServingId=w.parseNodeText(o);break;case"Category":n.categories.push({authority:o.getAttribute("authority")||null,value:w.parseNodeText(o)});break;case"Expires":n.expires=parseInt(w.parseNodeText(o),10);break;case"ViewableImpression":n.viewableImpression.push(X(o));break;case"Description":n.description=w.parseNodeText(o);break;case"Advertiser":n.advertiser={id:o.getAttribute("id")||null,value:w.parseNodeText(o)};break;case"Pricing":n.pricing={value:w.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":n.survey=w.parseNodeText(o);break;case"BlockedAdCategories":n.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:w.parseNodeText(o)})}}return r.length&&(n.adVerifications=n.adVerifications.concat(r)),n}function G(e,t){var r=_(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||w.parseBoolean(i),r.allowMultipleAds=!!n&&w.parseBoolean(n),r.fallbackOnNoAd=a?w.parseBoolean(a):null;var o=w.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=w.parseNodeText(o):(o=w.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=w.parseNodeText(w.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function z(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in w.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=w.parseNodeText(a),w.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=w.parseNodeText(a)}}var o=w.childByName(e,"TrackingEvents");o&&w.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=w.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function Y(e){var t=null,r=[];return e.some((function(e){return t=w.childByName(e,"AdVerifications")})),t&&(r=z(w.childrenByName(t,"Verification"))),r}function X(e){var t={};t.id=e.getAttribute("id")||null;var r=e.childNodes;for(var i in r){var n=r[i],a=n.nodeName,o=w.parseNodeText(n);if(("Viewable"===a||"NotViewable"===a||"ViewUndetermined"===a)&&o){var s=a.toLowerCase();Array.isArray(t[s])||(t[s]=[]),t[s].push(o)}}return t}var K=function(){function e(){n(this,e),this._handlers=[]}return o(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(i(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(i(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)})),t.parentURLs.push(e);var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},u=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:u},c);t.emit("VAST-resolved",d),ne(c.byteLength,u),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||Z,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parentURLs=[],this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||te,this.vastVersion=null,ne(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?N.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.parentURLs=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,c=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var u=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=w.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&u.length>1)break;var m=q(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:c});m.ad?(u.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:u.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return u}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,c=void 0===l?null:l,u=t.wrapperDepth,d=void 0===u?0:u,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=w.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:c,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=N.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth||-1!==i.parentURLs.indexOf(e.nextWrapperURL))return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=w.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&w.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(K),se=null,le={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},ce=function(){function e(){n(this,e),this.storage=this.initStorage()}return o(e,[{key:"initStorage",value:function(){if(se)return se;try{se="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){se=null}return se&&!this.isStorageDisabled(se)||(se=le).clear(),se}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),ue=function(){function e(t,r,i){n(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new oe,this.storage=i||new ce,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return o(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null;for(var l in n(this,a),(o=t.call(this)).ad=r,o.creative=i,o.variation=s,o.muted=!1,o.impressed=!1,o.skippable=!1,o.trackingEvents={},o.lastPercentage=0,o._alreadyTriggeredQuartiles={},o.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],o.creative.trackingEvents){var c=o.creative.trackingEvents[l];o.trackingEvents[l]=c.slice(0)}return C(o.creative)?o._initLinearTracking():o._initVariationTracking(),e&&o.on("start",(function(){e.lastSuccessfulAd=Date.now()})),o}return o(a,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){N.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(N.isValidTimeValue(e)&&"object"===i(r)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){N.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===i(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===i(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var r=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));var n=r.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===i(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===i(t)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);var n=this.clickThroughURLTemplate||e,a=r({},t);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=N.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.macros,n=void 0===r?{}:r,a=t.once,o=void 0!==a&&a;if("object"===i(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var t,i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=r({},n);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(i=t.universalAdIds)&&void 0!==i&&i.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),N.track(e,o,a)}},{key:"convertToTimecode",value:function(e){if(!N.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(N.addLeadingZeros(r,2),":").concat(N.addLeadingZeros(i,2),":").concat(N.addLeadingZeros(n,2),".").concat(N.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),a}(K);return e.VASTClient=ue,e.VASTParser=oe,e.VASTTracker=de,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); +var VAST=function(e){"use strict";function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(e){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}var g=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=A(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=w(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=N(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(T(s,t))}return i}function T(e,t){var r=(e=k(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return g.indexOf(e)>-1}));return 0===i.length?e:k(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function k(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function A(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function b(e){return/^(https?:\/\/|\/\/)/.test(e)}function R(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var L={track:function(e,t,r){y(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:y,extractURLsFromTemplates:A,filterValidUrlTemplates:function(e){return Array.isArray(e)?e.filter((function(e){return b(e.hasOwnProperty("url")?e.url:e)})):b(e)},containsTemplateObject:R,isTemplateObjectEqual:E,encodeURIComponentRFC3986:N,replaceUrlMacros:T,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce((function(e,t){return R(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:w};function U(e){return-1!==["true","TRUE","True","1"].indexOf(e)}function C(e){if(null==e)return-1;if(L.isNumeric(e))return parseInt(e);var t=e.split(":");if(3!==t.length)return-1;var r=t[2].split("."),i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));var n=parseInt(60*t[1]),a=parseInt(60*t[0]*60);return isNaN(a)||isNaN(n)||isNaN(i)||n>3600||i>60?-1:a+n+i}var I={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:U,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=U(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(h(e.viewableImpression),h(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var i=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),n=i.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){L.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=i.concat(e.creatives);var a=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,o=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(a&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),o&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&n.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=L.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,n)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){var s=t.creatives.filter((function(e){var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));s.length&&(e.creatives=e.creatives.concat(s))}}};function x(e,t){var r=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=I.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(I.parseAttributes(e));t.htmlResources=I.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=I.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=I.childrenByName(e,"StaticResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=I.parseNodeText(I.childByName(e,"AltText"))||null;var r=I.childByName(e,"TrackingEvents");r&&I.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=I.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=I.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:I.parseNodeText(e)}})),t.companionClickThroughURLTemplate=I.parseNodeText(I.childByName(e,"CompanionClickThrough"))||null;var i=I.childByName(e,"AdParameters");return i&&(t.adParameters={value:I.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),r}function S(e,t){var r,i=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=I.parseDuration(I.parseNodeText(I.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=I.parseDuration(n);var o=I.childByName(e,"VideoClicks");if(o){var s=I.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:I.parseNodeText(s)}:null,I.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})})),I.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})}))}var l=I.childByName(e,"AdParameters");l&&(i.adParameters={value:I.parseNodeText(l),xmlEncoded:l.getAttribute("xmlEncoded")||null}),I.childrenByName(e,"TrackingEvents").forEach((function(e){I.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=I.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(I.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),I.childrenByName(e,"MediaFiles").forEach((function(e){I.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=I.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=I.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=I.parseBoolean(i));return t}(e))}));var t=I.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:I.parseBoolean(e.variableDuration),fileURL:null}}(I.parseAttributes(e));return t.fileURL=I.parseNodeText(e),t}(t));var r=I.childByName(e,"ClosedCaptionFiles");r&&I.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(I.parseAttributes(e));t.fileURL=I.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=I.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var c={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};c.id=s.getAttribute("id"),c.fileURL=I.parseNodeText(s),c.delivery=l.delivery,c.codec=s.getAttribute("codec"),c.type=l.type,c.width=parseInt(l.width,10),c.height=parseInt(l.height,10),c.fileSize=parseInt(s.getAttribute("fileSize"),10),c.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=c}}));var c=I.childByName(e,"Icons");return c&&I.childrenByName(c,"Icon").forEach((function(e){i.icons.push(function(e){var t={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:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=I.parseDuration(e.getAttribute("offset")),t.duration=I.parseDuration(e.getAttribute("duration")),I.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=I.parseNodeText(e)})),I.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=I.parseNodeText(e)})),I.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=I.parseNodeText(e)}));var r=I.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=I.parseNodeText(I.childByName(r,"IconClickThrough")),I.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})}));var i=I.childByName(r,"IconClickFallbackImages");i&&I.childrenByName(i,"IconClickFallbackImage").forEach((function(e){t.iconClickFallbackImages.push({url:I.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=I.parseNodeText(I.childByName(e,"IconViewTracking")),t}(e))})),i}function O(e,t){var r=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return I.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;I.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=I.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),I.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=I.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=I.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=I.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),I.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=I.parseNodeText(e)})),I.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=I.parseNodeText(e)})),I.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=I.parseNodeText(e)}));var i=I.childByName(e,"AdParameters");i&&(t.adParameters={value:I.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=I.parseNodeText(I.childByName(e,"NonLinearClickThrough")),I.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})})),r.variations.push(t)})),r}function D(e){var t=[];return e.forEach((function(e){var r=V(e);r&&t.push(r)})),t}function V(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=V(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var c=I.parseNodeText(e);""!==c&&(r.value=c),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function P(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:B(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];I.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:I.parseNodeText(e)};n.push(t)}));var a=I.childByName(e,"CreativeExtensions");for(var o in a&&(r=D(I.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=S(s,i);break;case"NonLinearAds":l=O(s,i);break;case"CompanionAds":l=x(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function B(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var F={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function M(e,t){if(F[e.nodeName]&&F[e.nodeName].attributes){var r=F[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&q({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function j(e,t,r){var i=F[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!I.childByName(e,t)}));a.length>0&&q({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return I.childByName(e,t)}))||q({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function W(e){return e.children&&0!==e.children.length}function q(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var H={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),M(t,r),W(t)){j(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(I.copyNodeAttribute("id",e,s),I.copyNodeAttribute("sequence",e,s),I.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:Y(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:G(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function G(e,t){return!1===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allowMultipleAds&&e.getAttribute("sequence")?null:z(e,t)}function z(e,t){var r=[];t&&H.verifyRequiredValues(e,t);var i,n,a=e.childNodes,o=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(I.parseAttributes(e));for(var s in a){var l=a[s];switch(l.nodeName){case"Error":o.errorURLTemplates.push(I.parseNodeText(l));break;case"Impression":o.impressionURLTemplates.push({id:l.getAttribute("id")||null,url:I.parseNodeText(l)});break;case"Creatives":o.creatives=P(I.childrenByName(l,"Creative"));break;case"Extensions":var c=I.childrenByName(l,"Extension");o.extensions=D(c),o.adVerifications.length||(r=K(c));break;case"AdVerifications":o.adVerifications=X(I.childrenByName(l,"Verification"));break;case"AdSystem":o.system={value:I.parseNodeText(l),version:l.getAttribute("version")||null};break;case"AdTitle":o.title=I.parseNodeText(l);break;case"AdServingId":o.adServingId=I.parseNodeText(l);break;case"Category":o.categories.push({authority:l.getAttribute("authority")||null,value:I.parseNodeText(l)});break;case"Expires":o.expires=parseInt(I.parseNodeText(l),10);break;case"ViewableImpression":o.viewableImpression.push((n=void 0,n=function(e,t){var r=I.parseNodeText(t);return r&&e.push(r),e},{id:(i=l).getAttribute("id")||null,viewable:I.childrenByName(i,"Viewable").reduce(n,[]),notViewable:I.childrenByName(i,"NotViewable").reduce(n,[]),viewUndetermined:I.childrenByName(i,"ViewUndetermined").reduce(n,[])}));break;case"Description":o.description=I.parseNodeText(l);break;case"Advertiser":o.advertiser={id:l.getAttribute("id")||null,value:I.parseNodeText(l)};break;case"Pricing":o.pricing={value:I.parseNodeText(l),model:l.getAttribute("model")||null,currency:l.getAttribute("currency")||null};break;case"Survey":o.survey={value:I.parseNodeText(l),type:l.getAttribute("type")||null};break;case"BlockedAdCategories":o.blockedAdCategories.push({authority:l.getAttribute("authority")||null,value:I.parseNodeText(l)})}}return r.length&&(o.adVerifications=o.adVerifications.concat(r)),o}function Y(e,t){var r=z(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||I.parseBoolean(i),r.allowMultipleAds=!!n&&I.parseBoolean(n),r.fallbackOnNoAd=a?I.parseBoolean(a):null;var o=I.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=I.parseNodeText(o):(o=I.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=I.parseNodeText(I.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function X(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in I.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=I.parseNodeText(a),I.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=I.parseNodeText(a)}}var o=I.childByName(e,"TrackingEvents");o&&I.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=I.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function K(e){var t=null,r=[];return e.some((function(e){return t=I.childByName(e,"AdVerifications")})),t&&(r=X(I.childrenByName(t,"Verification"))),r}var Q=function(){function e(){n(this,e),this._handlers=[]}return o(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(i(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(i(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)}));var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},u=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:u},c);t.emit("VAST-resolved",d),ae(c.byteLength,u),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||J,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||re,this.vastVersion=null,ae(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?L.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,c=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var u=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=I.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&u.length>1)break;var m=_(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:c});m.ad?(u.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:u.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return u}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,c=void 0===l?null:l,u=t.wrapperDepth,d=void 0===u?0:u,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=I.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:c,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=L.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth)return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=I.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&I.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(Q),le=null,ce={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},ue=function(){function e(){n(this,e),this.storage=this.initStorage()}return o(e,[{key:"initStorage",value:function(){if(le)return le;try{le="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){le=null}return le&&!this.isStorageDisabled(le)||(le=ce).clear(),le}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),de=function(){function e(t,r,i){n(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new se,this.storage=i||new ue,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return o(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null,l=arguments.length>4&&void 0!==arguments[4]&&arguments[4];for(var c in n(this,a),(o=t.call(this)).ad=r,o.creative=i,o.variation=s,o.muted=l,o.impressed=!1,o.skippable=!1,o.trackingEvents={},o.lastPercentage=0,o._alreadyTriggeredQuartiles={},o.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],o.creative.trackingEvents){var u=o.creative.trackingEvents[c];o.trackingEvents[c]=u.slice(0)}return!function(e){return"linear"===e.type}(o.creative)?o._initVariationTracking():o._initLinearTracking(),e&&o.on("start",(function(){e.lastSuccessfulAd=Date.now()})),o}return o(a,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){L.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(L.isValidTimeValue(e)&&"object"===i(r)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){L.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"trackViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewable,t)}))}},{key:"trackNotViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.notViewable,t)}))}},{key:"trackUndeterminedImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewUndetermined,t)}))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===i(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===i(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var r=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));var n=r.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===i(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===i(t)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);var n=this.clickThroughURLTemplate||e,a=r({},t);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=L.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.macros,n=void 0===r?{}:r,a=t.once,o=void 0!==a&&a;if("object"===i(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=L.filterValidUrlTemplates(e),o=r({},i);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),L.track(a,o,n)}},{key:"convertToTimecode",value:function(e){if(!L.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(L.addLeadingZeros(r,2),":").concat(L.addLeadingZeros(i,2),":").concat(L.addLeadingZeros(n,2),".").concat(L.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),a}(Q);return e.VASTClient=de,e.VASTParser=se,e.VASTTracker=pe,e.parseDuration=C,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); diff --git a/dist/vast-client-node.js b/dist/vast-client-node.js index 7eb5988a..614e1558 100644 --- a/dist/vast-client-node.js +++ b/dist/vast-client-node.js @@ -4,17 +4,14 @@ Object.defineProperty(exports, '__esModule', { value: true }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } - return keys; } - function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; @@ -24,10 +21,8 @@ function _objectSpread2(target) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } - return target; } - function _typeof(obj) { "@babel/helpers - typeof"; @@ -37,23 +32,20 @@ function _typeof(obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); @@ -62,8 +54,8 @@ function _createClass(Constructor, protoProps, staticProps) { }); return Constructor; } - function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -74,15 +66,12 @@ function _defineProperty(obj, key, value) { } else { obj[key] = value; } - return obj; } - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, @@ -95,28 +84,23 @@ function _inherits(subClass, superClass) { }); if (superClass) _setPrototypeOf(subClass, superClass); } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; - return _setPrototypeOf(o, p); } - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; - try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; @@ -124,56 +108,43 @@ function _isNativeReflectConstruct() { return false; } } - function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return self; } - function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } - return _assertThisInitialized(self); } - function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), - result; - + result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } - return _possibleConstructorReturn(this, result); }; } - function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); @@ -182,18 +153,28 @@ function _unsupportedIterableToArray(o, minLen) { if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; } - function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} function createAd() { var adAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; @@ -248,14 +229,13 @@ function createCompanionAd() { expandedWidth: creativeAttributes.expandedWidth || null, expandedHeight: creativeAttributes.expandedHeight || null, apiFramework: creativeAttributes.apiFramework || null, - adSlotID: creativeAttributes.adSlotID || null, + adSlotId: creativeAttributes.adSlotId || null, pxratio: creativeAttributes.pxratio || '1', renderingMode: creativeAttributes.renderingMode || 'default', staticResources: [], htmlResources: [], iframeResources: [], adParameters: null, - xmlEncoded: null, altText: null, companionClickThroughURLTemplate: null, companionClickTrackingURLTemplates: [], @@ -280,13 +260,11 @@ function createCreative() { function createCreativeCompanion() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -298,7 +276,8 @@ function createCreativeCompanion() { }; } -var 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 +var 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) { @@ -310,6 +289,7 @@ function track(URLTemplates, macros, options) { } }); } + /** * Replace the provided URLTemplates with the given values * @@ -317,40 +297,36 @@ function track(URLTemplates, macros, options) { * @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) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var resolvedURLs = []; - var URLArray = extractURLsFromTemplates(URLTemplates); // Set default value for invalid ERRORCODE + var 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 - + } + // 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['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 (var macro in macros) { macros[macro] = encodeURIComponentRFC3986(macros[macro]); } - for (var URLTemplateKey in URLArray) { var 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, @@ -359,50 +335,42 @@ function resolveURLTemplates(URLTemplates) { * @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 - + url = replaceMacrosValues(url, macros); + // match any macros from the url that was not replaced var remainingMacros = url.match(/[^[\]]+(?=])/g); - if (!remainingMacros) { return url; } - var supportedRemainingMacros = remainingMacros.filter(function (macro) { return supportedMacros.indexOf(macro) > -1; }); - if (supportedRemainingMacros.length === 0) { return url; } - supportedRemainingMacros = supportedRemainingMacros.reduce(function (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) { var replacedMacrosUrl = url; - for (var key in macros) { - var value = macros[key]; // this will match [${key}] and %%${key}%% and replace it - + var 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 @@ -411,17 +379,38 @@ function replaceMacrosValues(url, macros) { * * @param {Array|String} URLTemplates - An array|string of url templates. */ - - function extractURLsFromTemplates(URLTemplates) { if (Array.isArray(URLTemplates)) { return URLTemplates.map(function (URLTemplate) { return URLTemplate && URLTemplate.hasOwnProperty('url') ? URLTemplate.url : URLTemplate; }); } - return URLTemplates; } + +/** + * Filter URLTemplates elements to keep only valid and safe URL templates. + * To be valid, urls should: + * - have the same protocol as the client + * or + * - be protocol-relative urls + * + * @param {Array} URLTemplates - A Array of string/object containing urls templates. + */ +function filterValidUrlTemplates(URLTemplates) { + if (Array.isArray(URLTemplates)) { + return URLTemplates.filter(function (urlTemplate) { + var url = urlTemplate.hasOwnProperty('url') ? urlTemplate.url : urlTemplate; + return isValidUrl(url); + }); + } + return isValidUrl(URLTemplates); +} +function isValidUrl(url) { + var 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 @@ -429,17 +418,15 @@ function extractURLsFromTemplates(URLTemplates) { * @param {Object} obj - The object who existence is to be checked. * @param {Array} list - List of objects. */ - - function containsTemplateObject(obj, list) { for (var 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 @@ -447,33 +434,30 @@ function containsTemplateObject(obj, list) { * @param {Object} obj1 * @param {Object} obj2 */ - - function isTemplateObjectEqual(obj1, obj2) { if (obj1 && obj2) { var obj1Properties = Object.getOwnPropertyNames(obj1); - var obj2Properties = Object.getOwnPropertyNames(obj2); // If number of properties is different, objects are not equivalent + var 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 - +} +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent function encodeURIComponentRFC3986(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return "%".concat(c.charCodeAt(0).toString(16)); }); } + /** * Return a string of the input number with leading zeros defined by the length param * @@ -482,22 +466,19 @@ function encodeURIComponentRFC3986(str) { * * @return {String} */ - - function addLeadingZeros(input) { var 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(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); } + /** * Joins two arrays of objects without duplicates * @@ -506,8 +487,6 @@ function flatten(arr) { * * @return {Array} */ - - function joinArrayOfUniqueTemplateObjs() { var arr1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var arr2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; @@ -518,10 +497,10 @@ function joinArrayOfUniqueTemplateObjs() { 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. @@ -530,16 +509,14 @@ function joinArrayOfUniqueTemplateObjs() { * * @return {Boolean} */ - - function isValidTimeValue(time) { return Number.isFinite(time) && time >= -2; } - var util = { track: track, resolveURLTemplates: resolveURLTemplates, extractURLsFromTemplates: extractURLsFromTemplates, + filterValidUrlTemplates: filterValidUrlTemplates, containsTemplateObject: containsTemplateObject, isTemplateObjectEqual: isTemplateObjectEqual, encodeURIComponentRFC3986: encodeURIComponentRFC3986, @@ -561,236 +538,200 @@ var util = { * @param {String} name - The name to look for. * @return {Object|undefined} */ - function childByName(node, name) { var childNodes = node.childNodes; - for (var childKey in childNodes) { var child = childNodes[childKey]; - if (child.nodeName === name) { return child; } } } + /** * 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) { var children = []; var childNodes = node.childNodes; - for (var childKey in childNodes) { var child = childNodes[childKey]; - if (child.nodeName === name) { children.push(child); } } - return children; } + /** * 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.indexOf('//') === 0) { var _location = location, - protocol = _location.protocol; + protocol = _location.protocol; return "".concat(protocol).concat(vastAdTagUrl); } - if (vastAdTagUrl.indexOf('://') === -1) { // Resolve relative URLs (mainly for unit testing) var 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'].indexOf(booleanString) !== -1; } + /** * 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) { var 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) { var nodeAttributes = element.attributes; var attributes = {}; - for (var i = 0; i < nodeAttributes.length; i++) { attributes[nodeAttributes[i].nodeName] = nodeAttributes[i].nodeValue; } - return attributes; } + /** * 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 - - + } + // 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); } - var durationComponents = durationString.split(':'); - if (durationComponents.length !== 3) { return -1; } - var secondsAndMS = durationComponents[2].split('.'); var seconds = parseInt(secondsAndMS[0]); - if (secondsAndMS.length === 2) { seconds += parseFloat("0.".concat(secondsAndMS[1])); } - var minutes = parseInt(durationComponents[1] * 60); var 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) { var splittedVAST = []; var lastAdPod = null; ads.forEach(function (ad, i) { if (ad.sequence) { ad.sequence = parseInt(ad.sequence, 10); - } // The current Ad may be the next Ad of an AdPod - - + } + // The current Ad may be the next Ad of an AdPod if (ad.sequence > 1) { - var lastAd = ads[i - 1]; // check if the current Ad is exactly the next one in the AdPod - + var 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 + } + // 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) { for (var attrKey in attributes) { var attribute = attributes[attrKey]; - if (attribute.nodeName && attribute.nodeValue && verificationObject.hasOwnProperty(attribute.nodeName)) { var value = attribute.nodeValue; - if (typeof verificationObject[attribute.nodeName] === 'boolean') { value = parseBoolean(value); } - verificationObject[attribute.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 = [].concat(_toConsumableArray(unwrappedAd.viewableImpression), _toConsumableArray(wrapper.viewableImpression)); - } // values from the child wrapper will be overridden - + } + // values from the child wrapper will be overridden unwrappedAd.followAdditionalWrappers = wrapper.followAdditionalWrappers; unwrappedAd.allowMultipleAds = wrapper.allowMultipleAds; unwrappedAd.fallbackOnNoAd = wrapper.fallbackOnNoAd; @@ -815,50 +756,56 @@ function mergeWrapperAdData(unwrappedAd, wrapper) { if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) { for (var eventName in wrapper.trackingEvents[creative.type]) { var 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 - + } + // 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 - + } + // 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 - + } + // pass wrapper companion trackers to all companions if (creative.type === 'companion' && wrapperCompanionClickTracking.length) { (creative.variations || []).forEach(function (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 + var wrapperCreativesWithIconsNode = wrapper.creatives.filter(function (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); + } + } +} var parserUtils = { childByName: childByName, childrenByName: childrenByName, @@ -883,7 +830,6 @@ var parserUtils = { * @param {Object} creativeAttributes - The attributes of the CompanionAd (optional). * @return {Object} creative - The creative object. */ - function parseCreativeCompanion(creativeElement, creativeAttributes) { var creative = createCreativeCompanion(creativeAttributes); creative.required = creativeElement.getAttribute('required') || null; @@ -906,22 +852,18 @@ function parseCreativeCompanion(creativeElement, creativeAttributes) { }, []); companionAd.altText = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'AltText')) || null; var trackingEventsElement = parserUtils.childByName(companionResource, 'TrackingEvents'); - if (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var 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(function (clickTrackingElement) { return { id: clickTrackingElement.getAttribute('id') || null, @@ -930,12 +872,12 @@ function parseCreativeCompanion(creativeElement, creativeAttributes) { }); companionAd.companionClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'CompanionClickThrough')) || null; var adParametersElement = parserUtils.childByName(companionResource, 'AdParameters'); - if (adParametersElement) { - companionAd.adParameters = parserUtils.parseNodeText(adParametersElement); - companionAd.xmlEncoded = adParametersElement.getAttribute('xmlEncoded') || null; + companionAd.adParameters = { + value: parserUtils.parseNodeText(adParametersElement), + xmlEncoded: adParametersElement.getAttribute('xmlEncoded') || null + }; } - return companionAd; }); return creative; @@ -943,13 +885,11 @@ function parseCreativeCompanion(creativeElement, creativeAttributes) { function createCreativeLinear() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -1000,7 +940,8 @@ function createIcon() { pxratio: '1', iconClickThroughURLTemplate: null, iconClickTrackingURLTemplates: [], - iconViewTrackingURLTemplate: null + iconViewTrackingURLTemplate: null, + iconClickFallbackImages: [] }; } @@ -1059,13 +1000,11 @@ function createMezzanine() { * @param {any} creativeAttributes - The attributes of the Linear (optional). * @return {Object} creative - The creativeLinear object. */ - function parseCreativeLinear(creativeElement, creativeAttributes) { var offset; var creative = createCreativeLinear(creativeAttributes); creative.duration = parserUtils.parseDuration(parserUtils.parseNodeText(parserUtils.childByName(creativeElement, 'Duration'))); var skipOffset = creativeElement.getAttribute('skipoffset'); - if (typeof skipOffset === 'undefined' || skipOffset === null) { creative.skipDelay = null; } else if (skipOffset.charAt(skipOffset.length - 1) === '%' && creative.duration !== -1) { @@ -1074,12 +1013,9 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { } else { creative.skipDelay = parserUtils.parseDuration(skipOffset); } - var videoClicksElement = parserUtils.childByName(creativeElement, 'VideoClicks'); - if (videoClicksElement) { var videoClickThroughElement = parserUtils.childByName(videoClicksElement, 'ClickThrough'); - if (videoClickThroughElement) { creative.videoClickThroughURLTemplate = { id: videoClickThroughElement.getAttribute('id') || null, @@ -1088,7 +1024,6 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { } else { creative.videoClickThroughURLTemplate = null; } - parserUtils.childrenByName(videoClicksElement, 'ClickTracking').forEach(function (clickTrackingElement) { creative.videoClickTrackingURLTemplates.push({ id: clickTrackingElement.getAttribute('id') || null, @@ -1102,37 +1037,32 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { }); }); } - var adParamsElement = parserUtils.childByName(creativeElement, 'AdParameters'); - if (adParamsElement) { - creative.adParameters = parserUtils.parseNodeText(adParamsElement); + creative.adParameters = { + value: parserUtils.parseNodeText(adParamsElement), + xmlEncoded: adParamsElement.getAttribute('xmlEncoded') || null + }; } - parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var 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); } }); @@ -1142,13 +1072,10 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { creative.mediaFiles.push(parseMediaFile(mediaFileElement)); }); var interactiveCreativeElement = parserUtils.childByName(mediaFilesElement, 'InteractiveCreativeFile'); - if (interactiveCreativeElement) { creative.interactiveCreativeFile = parseInteractiveCreativeFile(interactiveCreativeElement); } - var closedCaptionElements = parserUtils.childByName(mediaFilesElement, 'ClosedCaptionFiles'); - if (closedCaptionElements) { parserUtils.childrenByName(closedCaptionElements, 'ClosedCaptionFile').forEach(function (closedCaptionElement) { var closedCaptionFile = createClosedCaptionFile(parserUtils.parseAttributes(closedCaptionElement)); @@ -1156,10 +1083,8 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { creative.closedCaptionFiles.push(closedCaptionFile); }); } - var mezzanineElement = parserUtils.childByName(mediaFilesElement, 'Mezzanine'); var requiredAttributes = getRequiredAttributes(mezzanineElement, ['delivery', 'type', 'width', 'height']); - if (requiredAttributes) { var mezzanine = createMezzanine(); mezzanine.id = mezzanineElement.getAttribute('id'); @@ -1175,21 +1100,19 @@ function parseCreativeLinear(creativeElement, creativeAttributes) { } }); var iconsElement = parserUtils.childByName(creativeElement, 'Icons'); - if (iconsElement) { parserUtils.childrenByName(iconsElement, 'Icon').forEach(function (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) { var mediaFile = createMediaFile(); mediaFile.id = mediaFileElement.getAttribute('id'); @@ -1206,38 +1129,32 @@ function parseMediaFile(mediaFileElement) { mediaFile.width = parseInt(mediaFileElement.getAttribute('width') || 0); mediaFile.height = parseInt(mediaFileElement.getAttribute('height') || 0); var scalable = mediaFileElement.getAttribute('scalable'); - if (scalable && typeof scalable === 'string') { mediaFile.scalable = parserUtils.parseBoolean(scalable); } - var 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) { var 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) { var icon = createIcon(); icon.program = iconElement.getAttribute('program'); @@ -1262,7 +1179,6 @@ function parseIcon(iconElement) { icon.staticResource = parserUtils.parseNodeText(staticElement); }); var iconClicksElement = parserUtils.childByName(iconElement, 'IconClicks'); - if (iconClicksElement) { icon.iconClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(iconClicksElement, 'IconClickThrough')); parserUtils.childrenByName(iconClicksElement, 'IconClickTracking').forEach(function (iconClickTrackingElement) { @@ -1271,47 +1187,51 @@ function parseIcon(iconElement) { url: parserUtils.parseNodeText(iconClickTrackingElement) }); }); + var iconClickFallbackImagesElement = parserUtils.childByName(iconClicksElement, 'IconClickFallbackImages'); + if (iconClickFallbackImagesElement) { + parserUtils.childrenByName(iconClickFallbackImagesElement, 'IconClickFallbackImage').forEach(function (iconClickFallbackImageElement) { + icon.iconClickFallbackImages.push({ + url: parserUtils.parseNodeText(iconClickFallbackImageElement) || null, + width: iconClickFallbackImageElement.getAttribute('width') || null, + height: iconClickFallbackImageElement.getAttribute('height') || null + }); + }); + } } - icon.iconViewTrackingURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(iconElement, 'IconViewTracking')); return icon; } + /** * Parses an horizontal position into a String ('left' or 'right') or into a Number. * @param {String} xPosition - The x position to parse. * @return {String|Number} */ - - function parseXPosition(xPosition) { if (['left', 'right'].indexOf(xPosition) !== -1) { return xPosition; } - return parseInt(xPosition || 0); } + /** * Parses an vertical position into a String ('top' or 'bottom') or into a Number. * @param {String} yPosition - The x position to parse. * @return {String|Number} */ - - function parseYPosition(yPosition) { if (['top', 'bottom'].indexOf(yPosition) !== -1) { return yPosition; } - return parseInt(yPosition || 0); } + /** * Getting required attributes from element * @param {Object} element - DOM element * @param {Array} attributes - list of attributes * @return {Object|null} null if a least one element not present */ - - function getRequiredAttributes(element, attributes) { var values = {}; var error = false; @@ -1327,13 +1247,11 @@ function getRequiredAttributes(element, attributes) { function createCreativeNonLinear() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -1380,7 +1298,6 @@ function isNonLinearAd(ad) { * @param {any} creativeAttributes - The attributes of the NonLinear (optional). * @return {Object} creative - The CreativeNonLinear object. */ - function parseCreativeNonLinear(creativeElement, creativeAttributes) { var creative = createCreativeNonLinear(creativeAttributes); parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { @@ -1388,12 +1305,10 @@ function parseCreativeNonLinear(creativeElement, creativeAttributes) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { eventName = trackingElement.getAttribute('event'); trackingURLTemplate = parserUtils.parseNodeText(trackingElement); - if (eventName && trackingURLTemplate) { if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } - creative.trackingEvents[eventName].push(trackingURLTemplate); } }); @@ -1422,11 +1337,12 @@ function parseCreativeNonLinear(creativeElement, creativeAttributes) { nonlinearAd.staticResource = parserUtils.parseNodeText(staticElement); }); var adParamsElement = parserUtils.childByName(nonlinearResource, 'AdParameters'); - if (adParamsElement) { - nonlinearAd.adParameters = parserUtils.parseNodeText(adParamsElement); + nonlinearAd.adParameters = { + value: parserUtils.parseNodeText(adParamsElement), + xmlEncoded: adParamsElement.getAttribute('xmlEncoded') || null + }; } - nonlinearAd.nonlinearClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(nonlinearResource, 'NonLinearClickThrough')); parserUtils.childrenByName(nonlinearResource, 'NonLinearClickTracking').forEach(function (clickTrackingElement) { nonlinearAd.nonlinearClickTrackingURLTemplates.push({ @@ -1457,72 +1373,67 @@ function isEmptyExtension(extension) { * @param {String} type - The type of extensions to parse.(Ad|Creative) * @return {AdExtension[]|CreativeExtension[]} - The nodes parsed to extensions */ - function parseExtensions(extensions) { var exts = []; extensions.forEach(function (extNode) { var ext = _parseExtension(extNode); - if (ext) { exts.push(ext); } }); return exts; } + /** * Parses an extension child node * @param {Node} extNode - The extension node to parse * @return {AdExtension|CreativeExtension|null} - The node parsed to extension */ - function _parseExtension(extNode) { // Ignore comments if (extNode.nodeName === '#comment') return null; var ext = createExtension(); var extNodeAttrs = extNode.attributes; var childNodes = extNode.childNodes; - ext.name = extNode.nodeName; // Parse attributes + ext.name = extNode.nodeName; + // Parse attributes if (extNode.attributes) { for (var extNodeAttrKey in extNodeAttrs) { if (extNodeAttrs.hasOwnProperty(extNodeAttrKey)) { var extNodeAttr = extNodeAttrs[extNodeAttrKey]; - if (extNodeAttr.nodeName && extNodeAttr.nodeValue) { ext.attributes[extNodeAttr.nodeName] = extNodeAttr.nodeValue; } } } - } // Parse all children - + } + // Parse all children for (var childNodeKey in childNodes) { if (childNodes.hasOwnProperty(childNodeKey)) { var parsedChild = _parseExtension(childNodes[childNodeKey]); - if (parsedChild) { ext.children.push(parsedChild); } } } + /* Only parse value of Nodes with only eather no children or only a cdata or text to avoid useless parsing that would result to a concatenation of all children */ - - if (ext.children.length === 0 || ext.children.length === 1 && ['#cdata-section', '#text'].indexOf(ext.children[0].name) >= 0) { var txt = parserUtils.parseNodeText(extNode); - if (txt !== '') { ext.value = txt; - } // Remove the children if it's a cdata or simply text to avoid useless children - + } + // Remove the children if it's a cdata or simply text to avoid useless children ext.children = []; - } // Only return not empty objects to not pollute extentions - + } + // Only return not empty objects to not pollute extentions return isEmptyExtension(ext) ? null : ext; } @@ -1531,7 +1442,6 @@ function _parseExtension(extNode) { * @param {any} creativeNodes - The creative nodes to parse. * @return {Array} - An array of Creative objects. */ - function parseCreatives(creativeNodes) { var creatives = []; creativeNodes.forEach(function (creativeElement) { @@ -1552,54 +1462,49 @@ function parseCreatives(creativeNodes) { }); var creativeExtensions; var creativeExtensionsElement = parserUtils.childByName(creativeElement, 'CreativeExtensions'); - if (creativeExtensionsElement) { creativeExtensions = parseExtensions(parserUtils.childrenByName(creativeExtensionsElement, 'CreativeExtension')); } - for (var creativeTypeElementKey in creativeElement.childNodes) { var creativeTypeElement = creativeElement.childNodes[creativeTypeElementKey]; var parsedCreative = void 0; - switch (creativeTypeElement.nodeName) { case 'Linear': parsedCreative = parseCreativeLinear(creativeTypeElement, creativeAttributes); break; - case 'NonLinearAds': parsedCreative = parseCreativeNonLinear(creativeTypeElement, creativeAttributes); break; - case 'CompanionAds': parsedCreative = parseCreativeCompanion(creativeTypeElement, creativeAttributes); break; } - if (parsedCreative) { if (universalAdIds) { parsedCreative.universalAdIds = universalAdIds; } - if (creativeExtensions) { parsedCreative.creativeExtensions = creativeExtensions; } - creatives.push(parsedCreative); } } }); return creatives; } + /** * Parses the creative adId Attribute. * @param {any} creativeElement - The creative element to retrieve the adId from. * @return {String|null} */ - function parseCreativeAdIdAttribute(creativeElement) { - return creativeElement.getAttribute('AdID') || // VAST 2 spec - creativeElement.getAttribute('adID') || // VAST 3 spec - creativeElement.getAttribute('adId') || // VAST 4 spec + return creativeElement.getAttribute('AdID') || + // VAST 2 spec + creativeElement.getAttribute('adID') || + // VAST 3 spec + creativeElement.getAttribute('adId') || + // VAST 4 spec null; } @@ -1680,21 +1585,16 @@ var requiredValues = { * @emits VASTParser#VAST-warning * @param {undefined|Boolean} [isAdInline] - Passed recursively to itself. True if the node is contained inside a inLine tag. */ - function verifyRequiredValues(node, emit, isAdInline) { if (!node || !node.nodeName) { return; } - if (node.nodeName === 'InLine') { isAdInline = true; } - verifyRequiredAttributes(node, emit); - if (hasSubElements(node)) { verifyRequiredSubElements(node, emit, isAdInline); - for (var i = 0; i < node.children.length; i++) { verifyRequiredValues(node.children[i], emit, isAdInline); } @@ -1705,24 +1605,21 @@ function verifyRequiredValues(node, emit, isAdInline) { }, emit); } } + /** * Verify and trigger warnings if node required attributes are not set. * @param {Node} node - The node element. * @param {Function} emit - Emit function used to trigger Warning event. * @emits VASTParser#VAST-warning */ - - function verifyRequiredAttributes(node, emit) { if (!requiredValues[node.nodeName] || !requiredValues[node.nodeName].attributes) { return; } - var requiredAttributes = requiredValues[node.nodeName].attributes; var missingAttributes = requiredAttributes.filter(function (attributeName) { return !node.getAttribute(attributeName); }); - if (missingAttributes.length > 0) { emitMissingValueWarning({ name: node.nodeName, @@ -1731,6 +1628,7 @@ function verifyRequiredAttributes(node, emit) { }, emit); } } + /** * Verify and trigger warnings if node required sub element are not set. * @param {Node} node - The node element @@ -1738,24 +1636,19 @@ function verifyRequiredAttributes(node, emit) { * @param {Function} emit - Emit function used to trigger Warning event. * @emits VASTParser#VAST-warning */ - - function verifyRequiredSubElements(node, emit, isAdInline) { - var required = requiredValues[node.nodeName]; // Do not verify subelement if node is a child of wrapper, but verify it if node is the Wrapper itself + var required = requiredValues[node.nodeName]; + // Do not verify subelement if node is a child of wrapper, but verify it if node is the Wrapper itself // Wrapper child have no required subElement. (Only InLine does) - var isInWrapperButNotWrapperItself = !isAdInline && node.nodeName !== 'Wrapper'; - if (!required || isInWrapperButNotWrapperItself) { return; } - if (required.subElements) { var requiredSubElements = required.subElements; var missingSubElements = requiredSubElements.filter(function (subElementName) { return !parserUtils.childByName(node, subElementName); }); - if (missingSubElements.length > 0) { emitMissingValueWarning({ name: node.nodeName, @@ -1763,18 +1656,16 @@ function verifyRequiredSubElements(node, emit, isAdInline) { subElements: missingSubElements }, emit); } - } // When InLine format is used some nodes (i.e , , or ) - // require at least one of the following resources: StaticResource, IFrameResource, HTMLResource - + } + // When InLine format is used some nodes (i.e , , or ) + // require at least one of the following resources: StaticResource, IFrameResource, HTMLResource if (!isAdInline || !required.oneOfinLineResources) { return; } - var resourceFound = required.oneOfinLineResources.some(function (resource) { return parserUtils.childByName(node, resource); }); - if (!resourceFound) { emitMissingValueWarning({ name: node.nodeName, @@ -1783,16 +1674,16 @@ function verifyRequiredSubElements(node, emit, isAdInline) { }, emit); } } + /** * Check if a node has sub elements. * @param {Node} node - The node element. * @returns {Boolean} */ - - function hasSubElements(node) { return node.children && node.children.length !== 0; } + /** * Trigger Warning if a element is empty or has missing attributes/subelements/resources * @param {Object} missingElement - Object containing missing elements and values @@ -1804,16 +1695,13 @@ function hasSubElements(node) { * @param {Function} emit - Emit function used to trigger Warning event. * @emits VastParser#VAST-warning */ - - function emitMissingValueWarning(_ref, emit) { var name = _ref.name, - parentName = _ref.parentName, - attributes = _ref.attributes, - subElements = _ref.subElements, - oneOfResources = _ref.oneOfResources; + parentName = _ref.parentName, + attributes = _ref.attributes, + subElements = _ref.subElements, + oneOfResources = _ref.oneOfResources; var message = "Element '".concat(name, "'"); - if (attributes) { message += " missing required attribute(s) '".concat(attributes.join(', '), "' "); } else if (subElements) { @@ -1823,14 +1711,12 @@ function emitMissingValueWarning(_ref, emit) { } else { message += " is empty"; } - emit('VAST-warning', { message: message, parentElement: parentName, specVersion: 4.1 }); } - var parserVerification = { verifyRequiredValues: verifyRequiredValues, hasSubElements: hasSubElements, @@ -1851,29 +1737,22 @@ var parserVerification = { * @emits VASTParser#VAST-warning * @return {Object|undefined} - Object containing the ad and if it is wrapper/inline */ - function parseAd(adElement, emit) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - allowMultipleAds = _ref.allowMultipleAds, - followAdditionalWrappers = _ref.followAdditionalWrappers; - + allowMultipleAds = _ref.allowMultipleAds, + followAdditionalWrappers = _ref.followAdditionalWrappers; var childNodes = adElement.childNodes; - for (var adTypeElementKey in childNodes) { var adTypeElement = childNodes[adTypeElementKey]; - if (['Wrapper', 'InLine'].indexOf(adTypeElement.nodeName) === -1) { continue; } - if (adTypeElement.nodeName === 'Wrapper' && followAdditionalWrappers === false) { continue; } - parserUtils.copyNodeAttribute('id', adElement, adTypeElement); parserUtils.copyNodeAttribute('sequence', adElement, adTypeElement); parserUtils.copyNodeAttribute('adType', adElement, adTypeElement); - if (adTypeElement.nodeName === 'Wrapper') { return { ad: parseWrapper(adTypeElement, emit), @@ -1889,6 +1768,7 @@ function parseAd(adElement, emit) { } } } + /** * Parses an Inline * @param {Object} adElement Element - The VAST Inline element to parse. @@ -1897,20 +1777,18 @@ function parseAd(adElement, emit) { * @emits VASTParser#VAST-warning * @return {Object} ad - The ad object. */ - function parseInLine(adElement, emit) { var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - allowMultipleAds = _ref2.allowMultipleAds; - + allowMultipleAds = _ref2.allowMultipleAds; // if allowMultipleAds is set to false by wrapper attribute // only the first stand-alone Ad (with no sequence values) in the // requested VAST response is allowed so we won't parse ads with sequence if (allowMultipleAds === false && adElement.getAttribute('sequence')) { return null; } - return parseAdElement(adElement, emit); } + /** * Parses an ad type (Inline or Wrapper) * @param {Object} adTypeElement - The VAST Inline or Wrapper element to parse. @@ -1918,99 +1796,79 @@ function parseInLine(adElement, emit) { * @emits VASTParser#VAST-warning * @return {Object} ad - The ad object. */ - - function parseAdElement(adTypeElement, emit) { var adVerificationsFromExtensions = []; - if (emit) { parserVerification.verifyRequiredValues(adTypeElement, emit); } - var childNodes = adTypeElement.childNodes; var ad = createAd(parserUtils.parseAttributes(adTypeElement)); - for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - switch (node.nodeName) { case 'Error': ad.errorURLTemplates.push(parserUtils.parseNodeText(node)); break; - case 'Impression': ad.impressionURLTemplates.push({ id: node.getAttribute('id') || null, url: parserUtils.parseNodeText(node) }); break; - case 'Creatives': ad.creatives = parseCreatives(parserUtils.childrenByName(node, 'Creative')); break; - case 'Extensions': { var extNodes = parserUtils.childrenByName(node, 'Extension'); ad.extensions = parseExtensions(extNodes); + /* OMID specify adVerifications should be in extensions for VAST < 4.0 To avoid to put them on two different places in two different format we reparse it from extensions the same way than for an AdVerifications node. */ - if (!ad.adVerifications.length) { adVerificationsFromExtensions = _parseAdVerificationsFromExtensions(extNodes); } - break; } - case 'AdVerifications': ad.adVerifications = _parseAdVerifications(parserUtils.childrenByName(node, 'Verification')); break; - case 'AdSystem': ad.system = { value: parserUtils.parseNodeText(node), version: node.getAttribute('version') || null }; break; - case 'AdTitle': ad.title = parserUtils.parseNodeText(node); break; - case 'AdServingId': ad.adServingId = parserUtils.parseNodeText(node); break; - case 'Category': ad.categories.push({ authority: node.getAttribute('authority') || null, value: parserUtils.parseNodeText(node) }); break; - case 'Expires': ad.expires = parseInt(parserUtils.parseNodeText(node), 10); break; - case 'ViewableImpression': ad.viewableImpression.push(_parseViewableImpression(node)); break; - case 'Description': ad.description = parserUtils.parseNodeText(node); break; - case 'Advertiser': ad.advertiser = { id: node.getAttribute('id') || null, value: parserUtils.parseNodeText(node) }; break; - case 'Pricing': ad.pricing = { value: parserUtils.parseNodeText(node), @@ -2018,11 +1876,12 @@ function parseAdElement(adTypeElement, emit) { currency: node.getAttribute('currency') || null }; break; - case 'Survey': - ad.survey = parserUtils.parseNodeText(node); + ad.survey = { + value: parserUtils.parseNodeText(node), + type: node.getAttribute('type') || null + }; break; - case 'BlockedAdCategories': ad.blockedAdCategories.push({ authority: node.getAttribute('authority') || null, @@ -2031,13 +1890,12 @@ function parseAdElement(adTypeElement, emit) { break; } } - if (adVerificationsFromExtensions.length) { ad.adVerifications = ad.adVerifications.concat(adVerificationsFromExtensions); } - return ad; } + /** * Parses a Wrapper element without resolving the wrapped urls. * @param {Object} wrapperElement - The VAST Wrapper element to be parsed. @@ -2045,8 +1903,6 @@ function parseAdElement(adTypeElement, emit) { * @emits VASTParser#VAST-warning * @return {Ad} */ - - function parseWrapper(wrapperElement, emit) { var ad = parseAdElement(wrapperElement, emit); var followAdditionalWrappersValue = wrapperElement.getAttribute('followAdditionalWrappers'); @@ -2056,17 +1912,14 @@ function parseWrapper(wrapperElement, emit) { ad.allowMultipleAds = allowMultipleAdsValue ? parserUtils.parseBoolean(allowMultipleAdsValue) : false; ad.fallbackOnNoAd = fallbackOnNoAdValue ? parserUtils.parseBoolean(fallbackOnNoAdValue) : null; var wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURI'); - if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(wrapperURLElement); } else { wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURL'); - if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(parserUtils.childByName(wrapperURLElement, 'URL')); } } - ad.creatives.forEach(function (wrapperCreativeElement) { if (['linear', 'nonlinear'].indexOf(wrapperCreativeElement.type) !== -1) { // TrackingEvents Linear / NonLinear @@ -2074,172 +1927,139 @@ function parseWrapper(wrapperElement, emit) { if (!ad.trackingEvents) { ad.trackingEvents = {}; } - if (!ad.trackingEvents[wrapperCreativeElement.type]) { ad.trackingEvents[wrapperCreativeElement.type] = {}; } - var _loop = function _loop(eventName) { var urls = wrapperCreativeElement.trackingEvents[eventName]; - if (!Array.isArray(ad.trackingEvents[wrapperCreativeElement.type][eventName])) { ad.trackingEvents[wrapperCreativeElement.type][eventName] = []; } - urls.forEach(function (url) { ad.trackingEvents[wrapperCreativeElement.type][eventName].push(url); }); }; - for (var eventName in wrapperCreativeElement.trackingEvents) { _loop(eventName); } - } // ClickTracking - - + } + // ClickTracking if (wrapperCreativeElement.videoClickTrackingURLTemplates) { if (!Array.isArray(ad.videoClickTrackingURLTemplates)) { ad.videoClickTrackingURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged - - wrapperCreativeElement.videoClickTrackingURLTemplates.forEach(function (item) { ad.videoClickTrackingURLTemplates.push(item); }); - } // ClickThrough - - + } + // ClickThrough if (wrapperCreativeElement.videoClickThroughURLTemplate) { ad.videoClickThroughURLTemplate = wrapperCreativeElement.videoClickThroughURLTemplate; - } // CustomClick - - + } + // CustomClick if (wrapperCreativeElement.videoCustomClickURLTemplates) { if (!Array.isArray(ad.videoCustomClickURLTemplates)) { ad.videoCustomClickURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged - - wrapperCreativeElement.videoCustomClickURLTemplates.forEach(function (item) { ad.videoCustomClickURLTemplates.push(item); }); } } }); - if (ad.nextWrapperURL) { return ad; } } + /** * Parses the AdVerifications Element. * @param {Array} verifications - The array of verifications to parse. * @return {Array} */ - - function _parseAdVerifications(verifications) { var ver = []; verifications.forEach(function (verificationNode) { var verification = createAdVerification(); var childNodes = verificationNode.childNodes; parserUtils.assignAttributes(verificationNode.attributes, verification); - for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - switch (node.nodeName) { case 'JavaScriptResource': case 'ExecutableResource': verification.resource = parserUtils.parseNodeText(node); parserUtils.assignAttributes(node.attributes, verification); break; - case 'VerificationParameters': verification.parameters = parserUtils.parseNodeText(node); break; } } - var trackingEventsElement = parserUtils.childByName(verificationNode, 'TrackingEvents'); - if (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var trackingURLTemplate = parserUtils.parseNodeText(trackingElement); - if (eventName && trackingURLTemplate) { if (!Array.isArray(verification.trackingEvents[eventName])) { verification.trackingEvents[eventName] = []; } - verification.trackingEvents[eventName].push(trackingURLTemplate); } }); } - ver.push(verification); }); return ver; } + /** * Parses the AdVerifications Element from extension for versions < 4.0 * @param {Array} extensions - The array of extensions to parse. * @return {Array} */ - function _parseAdVerificationsFromExtensions(extensions) { var adVerificationsNode = null, - adVerifications = []; // Find the first (and only) AdVerifications node from extensions + adVerifications = []; + // Find the first (and only) AdVerifications node from extensions extensions.some(function (extension) { return adVerificationsNode = parserUtils.childByName(extension, 'AdVerifications'); - }); // Parse it if we get it + }); + // Parse it if we get it if (adVerificationsNode) { adVerifications = _parseAdVerifications(parserUtils.childrenByName(adVerificationsNode, 'Verification')); } - return adVerifications; } + /** * Parses the ViewableImpression Element. * @param {Object} viewableImpressionNode - The ViewableImpression node element. * @return {Object} viewableImpression - The viewableImpression object */ - function _parseViewableImpression(viewableImpressionNode) { - var viewableImpression = {}; - viewableImpression.id = viewableImpressionNode.getAttribute('id') || null; - var viewableImpressionChildNodes = viewableImpressionNode.childNodes; - - for (var viewableImpressionElementKey in viewableImpressionChildNodes) { - var viewableImpressionElement = viewableImpressionChildNodes[viewableImpressionElementKey]; - var viewableImpressionNodeName = viewableImpressionElement.nodeName; - var viewableImpressionNodeValue = parserUtils.parseNodeText(viewableImpressionElement); - - if (viewableImpressionNodeName !== 'Viewable' && viewableImpressionNodeName !== 'NotViewable' && viewableImpressionNodeName !== 'ViewUndetermined' || !viewableImpressionNodeValue) { - continue; - } else { - var viewableImpressionNodeNameLower = viewableImpressionNodeName.toLowerCase(); - - if (!Array.isArray(viewableImpression[viewableImpressionNodeNameLower])) { - viewableImpression[viewableImpressionNodeNameLower] = []; - } - - viewableImpression[viewableImpressionNodeNameLower].push(viewableImpressionNodeValue); - } - } - - return viewableImpression; + var regroupNodesUrl = function regroupNodesUrl(urls, node) { + var url = parserUtils.parseNodeText(node); + url && urls.push(url); + return urls; + }; + return { + id: viewableImpressionNode.getAttribute('id') || null, + viewable: parserUtils.childrenByName(viewableImpressionNode, 'Viewable').reduce(regroupNodesUrl, []), + notViewable: parserUtils.childrenByName(viewableImpressionNode, 'NotViewable').reduce(regroupNodesUrl, []), + viewUndetermined: parserUtils.childrenByName(viewableImpressionNode, 'ViewUndetermined').reduce(regroupNodesUrl, []) + }; } var EventEmitter = /*#__PURE__*/function () { function EventEmitter() { _classCallCheck(this, EventEmitter); - this._handlers = []; } + /** * Adds the event name and handler function to the end of the handlers array. * No checks are made to see if the handler has already been added. @@ -2249,26 +2069,22 @@ var EventEmitter = /*#__PURE__*/function () { * @param {Function} handler * @returns {EventEmitter} */ - - _createClass(EventEmitter, [{ key: "on", value: function on(event, handler) { if (typeof handler !== 'function') { throw new TypeError("The handler argument must be of type Function. Received type ".concat(_typeof(handler))); } - if (!event) { throw new TypeError("The event argument must be of type String. Received type ".concat(_typeof(event))); } - this._handlers.push({ event: event, handler: handler }); - return this; } + /** * Adds a one-time handler function for the named event. * The next time event is triggered, this handler is removed and then invoked. @@ -2276,19 +2092,18 @@ var EventEmitter = /*#__PURE__*/function () { * @param {Function} handler * @returns {EventEmitter} */ - }, { key: "once", value: function once(event, handler) { return this.on(event, onceWrap(this, event, handler)); } + /** * Removes all instances for the specified handler from the handler array for the named event. * @param {String} event * @param {Function} handler * @returns {EventEmitter} */ - }, { key: "off", value: function off(event, handler) { @@ -2297,6 +2112,7 @@ var EventEmitter = /*#__PURE__*/function () { }); return this; } + /** * Synchronously calls each of the handlers registered for the named event, * in the order they were registered, passing the supplied arguments to each. @@ -2304,36 +2120,31 @@ var EventEmitter = /*#__PURE__*/function () { * @param {...any} args list of arguments that will be used by the event handler * @returns {Boolean} true if the event had handlers, false otherwise. */ - }, { key: "emit", value: function emit(event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } - var called = false; - this._handlers.forEach(function (item) { if (item.event === '*') { called = true; item.handler.apply(item, [event].concat(args)); } - if (item.event === event) { called = true; item.handler.apply(item, args); } }); - return called; } + /** * Removes all listeners, or those of the specified named event. * @param {String} event * @returns {EventEmitter} */ - }, { key: "removeAllListeners", value: function removeAllListeners(event) { @@ -2341,18 +2152,17 @@ var EventEmitter = /*#__PURE__*/function () { this._handlers = []; return this; } - this._handlers = this._handlers.filter(function (item) { return item.event !== event; }); return this; } + /** * Returns the number of listeners listening to the named event. * @param {String} event * @returns {Number} */ - }, { key: "listenerCount", value: function listenerCount(event) { @@ -2360,12 +2170,12 @@ var EventEmitter = /*#__PURE__*/function () { return item.event === event; }).length; } + /** * Returns a copy of the array of listeners for the named event including those created by .once(). * @param {String} event * @returns {Function[]} */ - }, { key: "listeners", value: function listeners(event) { @@ -2373,15 +2183,14 @@ var EventEmitter = /*#__PURE__*/function () { if (item.event === event) { listeners.push(item.handler); } - return listeners; }, []); } + /** * Returns an array listing the events for which the emitter has registered handlers. * @returns {String[]} */ - }, { key: "eventNames", value: function eventNames() { @@ -2390,16 +2199,13 @@ var EventEmitter = /*#__PURE__*/function () { }); } }]); - return EventEmitter; }(); - function onceWrap(target, event, handler) { var state = { fired: false, wrapFn: undefined }; - function onceWrapper() { if (!state.fired) { target.off(event, state.wrapFn); @@ -2407,7 +2213,6 @@ function onceWrap(target, event, handler) { handler.bind(target).apply(void 0, arguments); } } - state.wrapFn = onceWrapper; return onceWrapper; } @@ -2415,25 +2220,18 @@ function onceWrap(target, event, handler) { var DEFAULT_TIMEOUT = 120000; var uri = require('url'); - var fs = require('fs'); - var http = require('http'); - var https = require('https'); - var DOMParser = require('@xmldom/xmldom').DOMParser; - function get$2(url, options, cb) { url = uri.parse(url); var httpModule = url.protocol === 'https:' ? https : http; - if (url.protocol === 'file:') { fs.readFile(uri.fileURLToPath(url.href), 'utf8', function (err, data) { if (err) { return cb(err); } - var xml = new DOMParser().parseFromString(data); cb(null, xml, { byteLength: Buffer.from(data).byteLength @@ -2460,27 +2258,22 @@ function get$2(url, options, cb) { }); req.on('error', function (err) { clearTimeout(timeoutId); - if (req.aborted) { cb(new Error("NodeURLHandler: Request timed out after ".concat(timeout, " ms.")), null, { statusCode: 408 // Request timeout - }); } else { cb(err); } }); - var startTimeout = function startTimeout() { return setTimeout(function () { return req.abort(); }, timeout); }; - timeoutId = startTimeout(); } } - var nodeURLHandler = { get: get$2 }; @@ -2488,22 +2281,18 @@ var nodeURLHandler = { function xhr() { try { var request = new window.XMLHttpRequest(); - if ('withCredentials' in request) { // check CORS support return request; } - return null; } catch (err) { return null; } } - function supported() { return !!xhr(); } - function handleLoad(request, cb) { if (request.status === 200) { cb(null, request.responseXML, { @@ -2514,50 +2303,40 @@ function handleLoad(request, cb) { handleFail(request, cb, false); } } - function handleFail(request, cb, isTimeout) { var statusCode = !isTimeout ? request.status : 408; // Request timeout - var msg = isTimeout ? "XHRURLHandler: Request timed out after ".concat(request.timeout, " ms (").concat(statusCode, ")") : "XHRURLHandler: ".concat(request.statusText, " (").concat(statusCode, ")"); cb(new Error(msg), null, { statusCode: statusCode }); } - function get$1(url, options, cb) { if (window.location.protocol === 'https:' && url.indexOf('http://') === 0) { return cb(new Error('XHRURLHandler: Cannot go from HTTPS to HTTP.')); } - try { var request = xhr(); request.open('GET', url); request.timeout = options.timeout || DEFAULT_TIMEOUT; request.withCredentials = options.withCredentials || false; request.overrideMimeType && request.overrideMimeType('text/xml'); - request.onload = function () { return handleLoad(request, cb); }; - request.onerror = function () { return handleFail(request, cb, false); }; - request.onabort = function () { return handleFail(request, cb, false); }; - request.ontimeout = function () { return handleFail(request, cb, true); }; - request.send(); } catch (error) { cb(new Error('XHRURLHandler: Unexpected error')); } } - var XHRURLHandler = { get: get$1, supported: supported @@ -2569,27 +2348,23 @@ function get(url, options, cb) { if (typeof options === 'function') { cb = options; } - options = {}; } - if (typeof window === 'undefined' || window === null) { return nodeURLHandler.get(url, options, cb); } else if (XHRURLHandler.supported()) { return XHRURLHandler.get(url, options, cb); } - return cb(new Error('Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler')); } - var urlHandler = { get: get }; function createVASTResponse(_ref) { var ads = _ref.ads, - errorURLTemplates = _ref.errorURLTemplates, - version = _ref.version; + errorURLTemplates = _ref.errorURLTemplates, + version = _ref.version; return { ads: ads || [], errorURLTemplates: errorURLTemplates || [], @@ -2600,20 +2375,21 @@ function createVASTResponse(_ref) { /* We decided to put the estimated bitrate separated from classes to persist it between different instances of vast client/parser */ + var estimatedBitrateCount = 0; var estimatedBitrate = 0; + /** * Calculate average estimated bitrate from the previous values and new entries * @param {Number} byteLength - The length of the response in bytes. * @param {Number} duration - The duration of the request in ms. */ - var updateEstimatedBitrate = function updateEstimatedBitrate(byteLength, duration) { if (!byteLength || !duration || byteLength <= 0 || duration <= 0) { return; - } // We want the bitrate in kb/s, byteLength are in bytes and duration in ms, just need to convert the byteLength because kb/s = b/ms - + } + // We want the bitrate in kb/s, byteLength are in bytes and duration in ms, just need to convert the byteLength because kb/s = b/ms var bitrate = byteLength * 8 / duration; estimatedBitrate = (estimatedBitrate * estimatedBitrateCount + bitrate) / ++estimatedBitrateCount; }; @@ -2623,30 +2399,25 @@ var DEFAULT_EVENT_DATA = { ERRORCODE: 900, extensions: [] }; + /** * This class provides methods to fetch and parse a VAST document. * @export * @class VASTParser * @extends EventEmitter */ - var VASTParser = /*#__PURE__*/function (_EventEmitter) { _inherits(VASTParser, _EventEmitter); - var _super = _createSuper(VASTParser); - /** * Creates an instance of VASTParser. * @constructor */ function VASTParser() { var _this; - _classCallCheck(this, VASTParser); - _this = _super.call(this); _this.remainingAds = []; - _this.parentURLs = []; _this.errorURLTemplates = []; _this.rootErrorURLTemplates = []; _this.maxWrapperDepth = null; @@ -2655,13 +2426,12 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { _this.parsingOptions = {}; return _this; } + /** * Adds a filter function to the array of filters which are called before fetching a VAST document. * @param {function} filter - The filter function to be added at the end of the array. * @return {void} */ - - _createClass(VASTParser, [{ key: "addURLTemplateFilter", value: function addURLTemplateFilter(filter) { @@ -2669,36 +2439,37 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { this.URLTemplateFilters.push(filter); } } + /** * Removes the last element of the url templates filters array. * @return {void} */ - }, { key: "removeURLTemplateFilter", value: function removeURLTemplateFilter() { this.URLTemplateFilters.pop(); } + /** * Returns the number of filters of the url templates filters array. * @return {Number} */ - }, { key: "countURLTemplateFilters", value: function countURLTemplateFilters() { return this.URLTemplateFilters.length; } + /** * Removes all the filter functions from the url templates filters array. * @return {void} */ - }, { key: "clearURLTemplateFilters", value: function clearURLTemplateFilters() { this.URLTemplateFilters = []; } + /** * Tracks the error provided in the errorCode parameter and emits a VAST-error event for the given error. * @param {Array} urlTemplates - An Array of url templates to use to make the tracking call. @@ -2707,37 +2478,36 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @emits VASTParser#VAST-error * @return {void} */ - }, { key: "trackVastError", value: function trackVastError(urlTemplates, errorCode) { for (var _len = arguments.length, data = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { data[_key - 2] = arguments[_key]; } - this.emit('VAST-error', Object.assign.apply(Object, [{}, DEFAULT_EVENT_DATA, errorCode].concat(data))); util.track(urlTemplates, errorCode); } + /** * Returns an array of errorURLTemplates for the VAST being parsed. * @return {Array} */ - }, { key: "getErrorURLTemplates", value: function getErrorURLTemplates() { return this.rootErrorURLTemplates.concat(this.errorURLTemplates); } + /** * Returns the estimated bitrate calculated from all previous requests * @returns The average of all estimated bitrates in kb/s. */ - }, { key: "getEstimatedBitrate", value: function getEstimatedBitrate() { return estimatedBitrate; } + /** * Fetches a VAST document for the given url. * Returns a Promise which resolves,rejects according to the result of the request. @@ -2749,12 +2519,10 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @emits VASTParser#VAST-resolved * @return {Promise} */ - }, { key: "fetchVAST", value: function fetchVAST(url) { var _this2 = this; - var wrapperDepth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var previousUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var wrapperAd = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; @@ -2763,11 +2531,7 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { _this2.URLTemplateFilters.forEach(function (filter) { url = filter(url); }); - - _this2.parentURLs.push(url); - var timeBeforeGet = Date.now(); - _this2.emit('VAST-resolving', { url: url, previousUrl: previousUrl, @@ -2776,7 +2540,6 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { timeout: _this2.fetchingOptions.timeout, wrapperAd: wrapperAd }); - _this2.urlHandler.get(url, _this2.fetchingOptions, function (error, xml) { var details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var deltaTime = Math.round(Date.now() - timeBeforeGet); @@ -2787,11 +2550,8 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { error: error, duration: deltaTime }, details); - _this2.emit('VAST-resolved', info); - updateEstimatedBitrate(details.byteLength, deltaTime); - if (error) { reject(error); } else { @@ -2800,11 +2560,11 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { }); }); } + /** * Inits the parsing properties of the class with the custom values provided as options. * @param {Object} options - The options to initialize a parsing sequence */ - }, { key: "initParsingStatus", value: function initParsingStatus() { @@ -2815,7 +2575,6 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { withCredentials: options.withCredentials }; this.maxWrapperDepth = options.wrapperLimit || DEFAULT_MAX_WRAPPER_DEPTH; - this.parentURLs = []; this.parsingOptions = { allowMultipleAds: options.allowMultipleAds }; @@ -2826,24 +2585,21 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { this.vastVersion = null; updateEstimatedBitrate(options.byteLength, options.requestDuration); } + /** * Resolves the next group of ads. If all is true resolves all the remaining ads. * @param {Boolean} all - If true all the remaining ads are resolved * @return {Promise} */ - }, { key: "getRemainingAds", value: function getRemainingAds(all) { var _this3 = this; - if (this.remainingAds.length === 0) { return Promise.reject(new Error('No more ads are available for the given VAST')); } - var ads = all ? util.flatten(this.remainingAds) : this.remainingAds.shift(); this.errorURLTemplates = []; - this.parentURLs = []; return this.resolveAds(ads, { wrapperDepth: 0, url: this.rootURL @@ -2851,6 +2607,7 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { return _this3.buildVASTResponse(resolvedAds); }); } + /** * Fetches and parses a VAST for the given url. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -2861,12 +2618,10 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "getAndParseVAST", value: function getAndParseVAST(url) { var _this4 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.initParsingStatus(options); this.URLTemplateFilters.forEach(function (filter) { @@ -2882,6 +2637,7 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { }); }); } + /** * Parses the given xml Object into a VASTResponse. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -2892,12 +2648,10 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "parseVAST", value: function parseVAST(vastXml) { var _this5 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.initParsingStatus(options); options.isRootVAST = true; @@ -2905,12 +2659,12 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { return _this5.buildVASTResponse(ads); }); } + /** * Builds a VASTResponse which can be returned. * @param {Array} ads - An Array of unwrapped ads * @return {Object} */ - }, { key: "buildVASTResponse", value: function buildVASTResponse(ads) { @@ -2922,6 +2676,7 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { this.completeWrapperResolving(response); return response; } + /** * Parses the given xml Object into an array of ads * Returns the array or throws an `Error` if an invalid VAST XML is provided @@ -2932,19 +2687,17 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @return {Array} * @throws {Error} `vastXml` must be a valid VAST XMLDocument */ - }, { key: "parseVastXml", value: function parseVastXml(vastXml, _ref) { var _ref$isRootVAST = _ref.isRootVAST, - isRootVAST = _ref$isRootVAST === void 0 ? false : _ref$isRootVAST, - _ref$url = _ref.url, - url = _ref$url === void 0 ? null : _ref$url, - _ref$wrapperDepth = _ref.wrapperDepth, - wrapperDepth = _ref$wrapperDepth === void 0 ? 0 : _ref$wrapperDepth, - allowMultipleAds = _ref.allowMultipleAds, - followAdditionalWrappers = _ref.followAdditionalWrappers; - + isRootVAST = _ref$isRootVAST === void 0 ? false : _ref$isRootVAST, + _ref$url = _ref.url, + url = _ref$url === void 0 ? null : _ref$url, + _ref$wrapperDepth = _ref.wrapperDepth, + wrapperDepth = _ref$wrapperDepth === void 0 ? 0 : _ref$wrapperDepth, + allowMultipleAds = _ref.allowMultipleAds, + followAdditionalWrappers = _ref.followAdditionalWrappers; // check if is a valid VAST document if (!vastXml || !vastXml.documentElement || vastXml.documentElement.nodeName !== 'VAST') { this.emit('VAST-ad-parsed', { @@ -2954,26 +2707,24 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { }); throw new Error('Invalid VAST XMLDocument'); } - var ads = []; var childNodes = vastXml.documentElement.childNodes; + /* Only parse the version of the Root VAST for now because we don't know yet how to * handle some cases like multiple wrappers in the same vast */ - var vastVersion = vastXml.documentElement.getAttribute('version'); - if (isRootVAST) { if (vastVersion) this.vastVersion = vastVersion; - } // Fill the VASTResponse object with ads and errorURLTemplates - + } + // Fill the VASTResponse object with ads and errorURLTemplates for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - if (node.nodeName === 'Error') { - var errorURLTemplate = parserUtils.parseNodeText(node); // Distinguish root VAST url templates from ad specific ones + var errorURLTemplate = parserUtils.parseNodeText(node); + // Distinguish root VAST url templates from ad specific ones isRootVAST ? this.rootErrorURLTemplates.push(errorURLTemplate) : this.errorURLTemplates.push(errorURLTemplate); } else if (node.nodeName === 'Ad') { // allowMultipleAds was introduced in VAST 3 @@ -2985,12 +2736,10 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { // (with no sequence values) in the requested VAST response is allowed break; } - var result = parseAd(node, this.emit.bind(this), { allowMultipleAds: allowMultipleAds, followAdditionalWrappers: followAdditionalWrappers }); - if (result.ad) { ads.push(result.ad); this.emit('VAST-ad-parsed', { @@ -3008,9 +2757,9 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { } } } - return ads; } + /** * Parses the given xml Object into an array of unwrapped ads. * Returns a Promise which resolves with the array or rejects with an error according to the result of the parsing. @@ -3021,33 +2770,30 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "parse", value: function parse(vastXml) { var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref2$url = _ref2.url, - url = _ref2$url === void 0 ? null : _ref2$url, - _ref2$resolveAll = _ref2.resolveAll, - resolveAll = _ref2$resolveAll === void 0 ? true : _ref2$resolveAll, - _ref2$wrapperSequence = _ref2.wrapperSequence, - wrapperSequence = _ref2$wrapperSequence === void 0 ? null : _ref2$wrapperSequence, - _ref2$previousUrl = _ref2.previousUrl, - previousUrl = _ref2$previousUrl === void 0 ? null : _ref2$previousUrl, - _ref2$wrapperDepth = _ref2.wrapperDepth, - wrapperDepth = _ref2$wrapperDepth === void 0 ? 0 : _ref2$wrapperDepth, - _ref2$isRootVAST = _ref2.isRootVAST, - isRootVAST = _ref2$isRootVAST === void 0 ? false : _ref2$isRootVAST, - followAdditionalWrappers = _ref2.followAdditionalWrappers, - allowMultipleAds = _ref2.allowMultipleAds; - - var ads = []; // allowMultipleAds was introduced in VAST 3 as wrapper attribute + _ref2$url = _ref2.url, + url = _ref2$url === void 0 ? null : _ref2$url, + _ref2$resolveAll = _ref2.resolveAll, + resolveAll = _ref2$resolveAll === void 0 ? true : _ref2$resolveAll, + _ref2$wrapperSequence = _ref2.wrapperSequence, + wrapperSequence = _ref2$wrapperSequence === void 0 ? null : _ref2$wrapperSequence, + _ref2$previousUrl = _ref2.previousUrl, + previousUrl = _ref2$previousUrl === void 0 ? null : _ref2$previousUrl, + _ref2$wrapperDepth = _ref2.wrapperDepth, + wrapperDepth = _ref2$wrapperDepth === void 0 ? 0 : _ref2$wrapperDepth, + _ref2$isRootVAST = _ref2.isRootVAST, + isRootVAST = _ref2$isRootVAST === void 0 ? false : _ref2$isRootVAST, + followAdditionalWrappers = _ref2.followAdditionalWrappers, + allowMultipleAds = _ref2.allowMultipleAds; + var ads = []; + // allowMultipleAds was introduced in VAST 3 as wrapper attribute // for retrocompatibility set it to true for vast pre-version 3 - if (this.vastVersion && parseFloat(this.vastVersion) < 3 && isRootVAST) { allowMultipleAds = true; } - try { ads = this.parseVastXml(vastXml, { isRootVAST: isRootVAST, @@ -3059,6 +2805,7 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { } catch (e) { return Promise.reject(e); } + /* Keep wrapper sequence value to not break AdPod when wrapper contain only one Ad. e.g,for a AdPod containing : - Inline with sequence=1 @@ -3069,25 +2816,23 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { - Inline sequence 2, - Inline sequence 3 */ - - if (ads.length === 1 && wrapperSequence !== undefined && wrapperSequence !== null) { ads[0].sequence = wrapperSequence; - } // Split the VAST in case we don't want to resolve everything at the first time - + } + // Split the VAST in case we don't want to resolve everything at the first time if (resolveAll === false) { - this.remainingAds = parserUtils.splitVAST(ads); // Remove the first element from the remaining ads array, since we're going to resolve that element - + this.remainingAds = parserUtils.splitVAST(ads); + // Remove the first element from the remaining ads array, since we're going to resolve that element ads = this.remainingAds.shift(); } - return this.resolveAds(ads, { wrapperDepth: wrapperDepth, previousUrl: previousUrl, url: url }); } + /** * Resolves an Array of ads, recursively calling itself with the remaining ads if a no ad * response is returned for the given array. @@ -3095,42 +2840,35 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @param {Object} options - An options Object containing resolving parameters * @return {Promise} */ - }, { key: "resolveAds", value: function resolveAds() { var _this6 = this; - var ads = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var _ref3 = arguments.length > 1 ? arguments[1] : undefined, - wrapperDepth = _ref3.wrapperDepth, - previousUrl = _ref3.previousUrl, - url = _ref3.url; - + wrapperDepth = _ref3.wrapperDepth, + previousUrl = _ref3.previousUrl, + url = _ref3.url; var resolveWrappersPromises = []; previousUrl = url; ads.forEach(function (ad) { var resolveWrappersPromise = _this6.resolveWrappers(ad, wrapperDepth, previousUrl); - resolveWrappersPromises.push(resolveWrappersPromise); }); return Promise.all(resolveWrappersPromises).then(function (unwrappedAds) { var resolvedAds = util.flatten(unwrappedAds); - if (!resolvedAds && _this6.remainingAds.length > 0) { var remainingAdsToResolve = _this6.remainingAds.shift(); - return _this6.resolveAds(remainingAdsToResolve, { wrapperDepth: wrapperDepth, previousUrl: previousUrl, url: url }); } - return resolvedAds; }); } + /** * Resolves the wrappers for the given ad in a recursive way. * Returns a Promise which resolves with the unwrapped ad or rejects with an error. @@ -3139,44 +2877,38 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { * @param {String} previousUrl - The previous vast url. * @return {Promise} */ - }, { key: "resolveWrappers", value: function resolveWrappers(ad, wrapperDepth, previousUrl) { var _this7 = this; - return new Promise(function (resolve) { var _this7$parsingOptions; - // Going one level deeper in the wrapper chain - wrapperDepth++; // We already have a resolved VAST ad, no need to resolve wrapper - + wrapperDepth++; + // We already have a resolved VAST ad, no need to resolve wrapper if (!ad.nextWrapperURL) { delete ad.nextWrapperURL; return resolve(ad); } - - if (wrapperDepth >= _this7.maxWrapperDepth || _this7.parentURLs.indexOf(ad.nextWrapperURL) !== -1) { + if (wrapperDepth >= _this7.maxWrapperDepth) { // Wrapper limit reached, as defined by the video player. // Too many Wrapper responses have been received with no InLine response. ad.errorCode = 302; delete ad.nextWrapperURL; return resolve(ad); - } // Get full URL - + } + // Get full URL ad.nextWrapperURL = parserUtils.resolveVastAdTagURI(ad.nextWrapperURL, previousUrl); - _this7.URLTemplateFilters.forEach(function (filter) { ad.nextWrapperURL = filter(ad.nextWrapperURL); - }); // If allowMultipleAds is set inside the parameter 'option' of public method - // override the vast value by the one provided - - - var allowMultipleAds = (_this7$parsingOptions = _this7.parsingOptions.allowMultipleAds) !== null && _this7$parsingOptions !== void 0 ? _this7$parsingOptions : ad.allowMultipleAds; // sequence doesn't carry over in wrapper element + }); + // If allowMultipleAds is set inside the parameter 'option' of public method + // override the vast value by the one provided + var allowMultipleAds = (_this7$parsingOptions = _this7.parsingOptions.allowMultipleAds) !== null && _this7$parsingOptions !== void 0 ? _this7$parsingOptions : ad.allowMultipleAds; + // sequence doesn't carry over in wrapper element var wrapperSequence = ad.sequence; - _this7.fetchVAST(ad.nextWrapperURL, wrapperDepth, previousUrl, ad).then(function (xml) { return _this7.parse(xml, { url: ad.nextWrapperURL, @@ -3187,13 +2919,11 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { allowMultipleAds: allowMultipleAds }).then(function (unwrappedAds) { delete ad.nextWrapperURL; - if (unwrappedAds.length === 0) { // No ads returned by the wrappedResponse, discard current creatives ad.creatives = []; return resolve(ad); } - unwrappedAds.forEach(function (unwrappedAd) { if (unwrappedAd) { parserUtils.mergeWrapperAdData(unwrappedAd, ad); @@ -3210,17 +2940,18 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { }); }); } + /** * Takes care of handling errors when the wrappers are resolved. * @param {Object} vastResponse - A resolved VASTResponse. */ - }, { key: "completeWrapperResolving", value: function completeWrapperResolving(vastResponse) { // We've to wait for all elements to be parsed before handling error so we can: // - Send computed extensions data // - Ping all URIs defined across VAST files + // No Ad case - The parser never bump into an element if (vastResponse.ads.length === 0) { this.trackVastError(vastResponse.errorURLTemplates, { @@ -3232,7 +2963,6 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { // - No Creative case - The parser has dealt with soma or/and an elements // but no creative was found var ad = vastResponse.ads[index]; - if (ad.errorCode || ad.creatives.length === 0) { this.trackVastError(ad.errorURLTemplates.concat(vastResponse.errorURLTemplates), { ERRORCODE: ad.errorCode || 303 @@ -3249,17 +2979,16 @@ var VASTParser = /*#__PURE__*/function (_EventEmitter) { } } }]); - return VASTParser; }(EventEmitter); var storage = null; + /** * This Object represents a default storage to be used in case no other storage is available. * @constant * @type {Object} */ - var DEFAULT_STORAGE = { data: {}, length: 0, @@ -3279,13 +3008,13 @@ var DEFAULT_STORAGE = { this.length = 0; } }; + /** * This class provides an wrapper interface to the a key-value storage. * It uses localStorage, sessionStorage or a custom storage if none of the two is available. * @export * @class Storage */ - var Storage = /*#__PURE__*/function () { /** * Creates an instance of Storage. @@ -3293,35 +3022,31 @@ var Storage = /*#__PURE__*/function () { */ function Storage() { _classCallCheck(this, Storage); - this.storage = this.initStorage(); } + /** * Provides a singleton instance of the wrapped storage. * @return {Object} */ - - _createClass(Storage, [{ key: "initStorage", value: function initStorage() { if (storage) { return storage; } - try { storage = typeof window !== 'undefined' && window !== null ? window.localStorage || window.sessionStorage : null; } catch (storageError) { storage = null; } - if (!storage || this.isStorageDisabled(storage)) { storage = DEFAULT_STORAGE; storage.clear(); } - return storage; } + /** * Check if storage is disabled (like in certain cases with private browsing). * In Safari (Mac + iOS) when private browsing is ON, localStorage is read only @@ -3329,15 +3054,12 @@ var Storage = /*#__PURE__*/function () { * @param {Object} testStorage - The storage to check. * @return {Boolean} */ - }, { key: "isStorageDisabled", value: function isStorageDisabled(testStorage) { var testValue = '__VASTStorage__'; - try { testStorage.setItem(testValue, testValue); - if (testStorage.getItem(testValue) !== testValue) { testStorage.removeItem(testValue); return true; @@ -3345,55 +3067,53 @@ var Storage = /*#__PURE__*/function () { } catch (e) { return true; } - testStorage.removeItem(testValue); return false; } + /** * Returns the value for the given key. If the key does not exist, null is returned. * @param {String} key - The key to retrieve the value. * @return {any} */ - }, { key: "getItem", value: function getItem(key) { return this.storage.getItem(key); } + /** * Adds or updates the value for the given key. * @param {String} key - The key to modify the value. * @param {any} value - The value to be associated with the key. * @return {any} */ - }, { key: "setItem", value: function setItem(key, value) { return this.storage.setItem(key, value); } + /** * Removes an item for the given key. * @param {String} key - The key to remove the value. * @return {any} */ - }, { key: "removeItem", value: function removeItem(key) { return this.storage.removeItem(key); } + /** * Removes all the items from the storage. */ - }, { key: "clear", value: function clear() { return this.storage.clear(); } }]); - return Storage; }(); @@ -3403,7 +3123,6 @@ var Storage = /*#__PURE__*/function () { * @export * @class VASTClient */ - var VASTClient = /*#__PURE__*/function () { /** * Creates an instance of VASTClient. @@ -3414,7 +3133,6 @@ var VASTClient = /*#__PURE__*/function () { */ function VASTClient(cappingFreeLunch, cappingMinimumTimeInterval, customStorage) { _classCallCheck(this, VASTClient); - this.cappingFreeLunch = cappingFreeLunch || 0; this.cappingMinimumTimeInterval = cappingMinimumTimeInterval || 0; this.defaultOptions = { @@ -3422,21 +3140,19 @@ var VASTClient = /*#__PURE__*/function () { timeout: 0 }; this.vastParser = new VASTParser(); - this.storage = customStorage || new Storage(); // Init values if not already set + this.storage = customStorage || new Storage(); + // Init values if not already set if (this.lastSuccessfulAd === undefined) { this.lastSuccessfulAd = 0; } - if (this.totalCalls === undefined) { this.totalCalls = 0; } - if (this.totalCallsTimeout === undefined) { this.totalCallsTimeout = 0; } } - _createClass(VASTClient, [{ key: "getParser", value: function getParser() { @@ -3466,27 +3182,28 @@ var VASTClient = /*#__PURE__*/function () { set: function set(value) { this.storage.setItem('vast-client-total-calls-timeout', value); } + /** * Returns a boolean indicating if there are more ads to resolve for the current parsing. * @return {Boolean} */ - }, { key: "hasRemainingAds", value: function hasRemainingAds() { return this.vastParser.remainingAds.length > 0; } + /** * Resolves the next group of ads. If all is true resolves all the remaining ads. * @param {Boolean} all - If true all the remaining ads are resolved * @return {Promise} */ - }, { key: "getNextAds", value: function getNextAds(all) { return this.vastParser.getRemainingAds(all); } + /** * Gets a parsed VAST document for the given url, applying the skipping rules defined. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -3494,44 +3211,41 @@ var VASTClient = /*#__PURE__*/function () { * @param {Object} options - An optional Object of parameters to be applied in the process. * @return {Promise} */ - }, { key: "get", value: function get(url) { var _this = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var now = Date.now(); - options = Object.assign({}, this.defaultOptions, options); // By default the client resolves only the first Ad or AdPod + options = Object.assign({}, this.defaultOptions, options); + // By default the client resolves only the first Ad or AdPod if (!options.hasOwnProperty('resolveAll')) { options.resolveAll = false; - } // Check totalCallsTimeout (first call + 1 hour), if older than now, + } + + // Check totalCallsTimeout (first call + 1 hour), if older than now, // reset totalCalls number, by this way the client will be eligible again // for freelunch capping - - if (this.totalCallsTimeout < now) { this.totalCalls = 1; this.totalCallsTimeout = now + 60 * 60 * 1000; } else { this.totalCalls++; } - return new Promise(function (resolve, reject) { if (_this.cappingFreeLunch >= _this.totalCalls) { return reject(new Error("VAST call canceled \u2013 FreeLunch capping not reached yet ".concat(_this.totalCalls, "/").concat(_this.cappingFreeLunch))); } + var timeSinceLastCall = now - _this.lastSuccessfulAd; - var timeSinceLastCall = now - _this.lastSuccessfulAd; // Check timeSinceLastCall to be a positive number. If not, this mean the + // Check timeSinceLastCall to be a positive number. If not, this mean the // previous was made in the future. We reset lastSuccessfulAd value - if (timeSinceLastCall < 0) { _this.lastSuccessfulAd = 0; } else if (timeSinceLastCall < _this.cappingMinimumTimeInterval) { return reject(new Error("VAST call canceled \u2013 (".concat(_this.cappingMinimumTimeInterval, ")ms minimum interval reached"))); } - _this.vastParser.getAndParseVAST(url, options).then(function (response) { return resolve(response); })["catch"](function (err) { @@ -3540,7 +3254,6 @@ var VASTClient = /*#__PURE__*/function () { }); } }]); - return VASTClient; }(); @@ -3549,8 +3262,8 @@ var VASTClient = /*#__PURE__*/function () { * @constant * @type {Number} */ - var DEFAULT_SKIP_DELAY = -1; + /** * This class provides methods to track an ad execution. * @@ -3558,12 +3271,9 @@ var DEFAULT_SKIP_DELAY = -1; * @class VASTTracker * @extends EventEmitter */ - var VASTTracker = /*#__PURE__*/function (_EventEmitter) { _inherits(VASTTracker, _EventEmitter); - var _super = _createSuper(VASTTracker); - /** * Creates an instance of VASTTracker. * @@ -3571,62 +3281,60 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Ad} ad - The ad to track. * @param {Creative} creative - The creative to track. * @param {Object} [variation=null] - An optional variation of the creative. + * @param {Boolean} [muted=false] - The initial muted state of the video. * @constructor */ function VASTTracker(client, ad, creative) { var _this; - var variation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - + var muted = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; _classCallCheck(this, VASTTracker); - _this = _super.call(this); _this.ad = ad; _this.creative = creative; _this.variation = variation; - _this.muted = false; + _this.muted = muted; _this.impressed = false; _this.skippable = false; - _this.trackingEvents = {}; // We need to keep the last percentage of the tracker in order to + _this.trackingEvents = {}; + // We need to keep the last percentage of the tracker in order to // calculate to trigger the events when the VAST duration is short - _this.lastPercentage = 0; - _this._alreadyTriggeredQuartiles = {}; // Tracker listeners should be notified with some events + _this._alreadyTriggeredQuartiles = {}; + // Tracker listeners should be notified with some events // no matter if there is a tracking URL or not + _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; - _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; // Duplicate the creative's trackingEvents property so we can alter it - + // Duplicate the creative's trackingEvents property so we can alter it for (var eventName in _this.creative.trackingEvents) { var events = _this.creative.trackingEvents[eventName]; _this.trackingEvents[eventName] = events.slice(0); - } // Nonlinear and companion creatives provide some tracking information at a variation level + } + + // Nonlinear and companion creatives provide some tracking information at a variation level // While linear creatives provided that at a creative level. That's why we need to // differentiate how we retrieve some tracking information. - - if (isCreativeLinear(_this.creative)) { _this._initLinearTracking(); } else { _this._initVariationTracking(); - } // If the tracker is associated with a client we add a listener to the start event - // to update the lastSuccessfulAd property. - + } + // If the tracker is associated with a client we add a listener to the start event + // to update the lastSuccessfulAd property. if (client) { _this.on('start', function () { client.lastSuccessfulAd = Date.now(); }); } - return _this; } + /** * Init the custom tracking options for linear creatives. * * @return {void} */ - - _createClass(VASTTracker, [{ key: "_initLinearTracking", value: function _initLinearTracking() { @@ -3636,35 +3344,36 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate; this.clickTrackingURLTemplates = this.creative.videoClickTrackingURLTemplates; } + /** * Init the custom tracking options for nonlinear and companion creatives. * These options are provided in the variation Object. * * @return {void} */ - }, { key: "_initVariationTracking", value: function _initVariationTracking() { this.linear = false; - this.skipDelay = DEFAULT_SKIP_DELAY; // If no variation has been provided there's nothing else to set + this.skipDelay = DEFAULT_SKIP_DELAY; + // If no variation has been provided there's nothing else to set if (!this.variation) { return; - } // Duplicate the variation's trackingEvents property so we can alter it - + } + // Duplicate the variation's trackingEvents property so we can alter it for (var eventName in this.variation.trackingEvents) { - var events = this.variation.trackingEvents[eventName]; // If for the given eventName we already had some trackingEvents provided by the creative - // we want to keep both the creative trackingEvents and the variation ones + var events = this.variation.trackingEvents[eventName]; + // If for the given eventName we already had some trackingEvents provided by the creative + // we want to keep both the creative trackingEvents and the variation ones if (this.trackingEvents[eventName]) { this.trackingEvents[eventName] = this.trackingEvents[eventName].concat(events.slice(0)); } else { this.trackingEvents[eventName] = events.slice(0); } } - if (isNonLinearAd(this.variation)) { this.clickThroughURLTemplate = this.variation.nonlinearClickThroughURLTemplate; this.clickTrackingURLTemplates = this.variation.nonlinearClickTrackingURLTemplates; @@ -3674,12 +3383,12 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { this.clickTrackingURLTemplates = this.variation.companionClickTrackingURLTemplates; } } + /** * Sets the duration of the ad and updates the quartiles based on that. * * @param {Number} duration - The duration of the ad. */ - }, { key: "setDuration", value: function setDuration(duration) { @@ -3687,15 +3396,15 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { if (!util.isValidTimeValue(duration)) { return; } - - this.assetDuration = duration; // beware of key names, theses are also used as event names - + this.assetDuration = duration; + // beware of key names, theses are also used as event names this.quartiles = { firstQuartile: Math.round(25 * this.assetDuration) / 100, midpoint: Math.round(50 * this.assetDuration) / 100, thirdQuartile: Math.round(75 * this.assetDuration) / 100 }; } + /** * Sets the duration of the ad and updates the quartiles based on that. * This is required for tracking time related events. @@ -3711,21 +3420,16 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#midpoint * @emits VASTTracker#thirdQuartile */ - }, { key: "setProgress", value: function setProgress(progress) { var _this2 = this; - var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - // check if progress is a valid time input if (!util.isValidTimeValue(progress) || _typeof(macros) !== 'object') { return; } - var skipDelay = this.skipDelay || DEFAULT_SKIP_DELAY; - if (skipDelay !== -1 && !this.skippable) { if (skipDelay > progress) { this.emit('skip-countdown', skipDelay - progress); @@ -3734,46 +3438,38 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { this.emit('skip-countdown', 0); } } - if (this.assetDuration > 0) { var percent = Math.round(progress / this.assetDuration * 100); var events = []; - if (progress > 0) { events.push('start'); - for (var i = this.lastPercentage; i < percent; i++) { events.push("progress-".concat(i + 1, "%")); } - events.push("progress-".concat(Math.round(progress))); - for (var quartile in this.quartiles) { if (this.isQuartileReached(quartile, this.quartiles[quartile], progress)) { events.push(quartile); this._alreadyTriggeredQuartiles[quartile] = true; } } - this.lastPercentage = percent; } - events.forEach(function (eventName) { _this2.track(eventName, { macros: macros, once: true }); }); - if (progress < this.progress) { this.track('rewind', { macros: macros }); } } - this.progress = progress; } + /** * Checks if a quartile has been reached without have being triggered already. * @@ -3783,18 +3479,17 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * * @return {Boolean} */ - }, { key: "isQuartileReached", value: function isQuartileReached(quartile, time, progress) { - var quartileReached = false; // if quartile time already reached and never triggered - + var quartileReached = false; + // if quartile time already reached and never triggered if (time <= progress && !this._alreadyTriggeredQuartiles[quartile]) { quartileReached = true; } - return quartileReached; } + /** * Updates the mute state and calls the mute/unmute tracking URLs. * @@ -3803,24 +3498,21 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#mute * @emits VASTTracker#unmute */ - }, { key: "setMuted", value: function setMuted(muted) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof muted !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.muted !== muted) { this.track(muted ? 'mute' : 'unmute', { macros: macros }); } - this.muted = muted; } + /** * Update the pause state and call the resume/pause tracking URLs. * @@ -3829,24 +3521,21 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#pause * @emits VASTTracker#resume */ - }, { key: "setPaused", value: function setPaused(paused) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof paused !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.paused !== paused) { this.track(paused ? 'pause' : 'resume', { macros: macros }); } - this.paused = paused; } + /** * Updates the fullscreen state and calls the fullscreen tracking URLs. * @@ -3855,24 +3544,21 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#fullscreen * @emits VASTTracker#exitFullscreen */ - }, { key: "setFullscreen", value: function setFullscreen(fullscreen) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof fullscreen !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.fullscreen !== fullscreen) { this.track(fullscreen ? 'fullscreen' : 'exitFullscreen', { macros: macros }); } - this.fullscreen = fullscreen; } + /** * Updates the expand state and calls the expand/collapse tracking URLs. * @@ -3883,16 +3569,13 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#collapse * @emits VASTTracker#playerCollapse */ - }, { key: "setExpand", value: function setExpand(expanded) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof expanded !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.expanded !== expanded) { this.track(expanded ? 'expand' : 'collapse', { macros: macros @@ -3901,9 +3584,9 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { macros: macros }); } - this.expanded = expanded; } + /** * Must be called if you want to overwrite the Skipoffset value. * This will init the skip countdown duration. Then, every time setProgress() is called, @@ -3912,31 +3595,27 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * * @param {Number} duration - The time in seconds until the skip button is displayed. */ - }, { key: "setSkipDelay", value: function setSkipDelay(duration) { if (!util.isValidTimeValue(duration)) { return; } - this.skipDelay = duration; } + /** * Tracks an impression (can be called only once). * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#creativeView */ - }, { key: "trackImpression", value: function trackImpression() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - if (!this.impressed) { this.impressed = true; this.trackURLs(this.ad.impressionURLTemplates, macros); @@ -3945,26 +3624,76 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { }); } } + + /** + * Tracks Viewable impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackViewableImpression", + value: function trackViewableImpression() { + var _this3 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this3.trackURLs(impression.viewable, macros); + }); + } + + /** + * Tracks NotViewable impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackNotViewableImpression", + value: function trackNotViewableImpression() { + var _this4 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this4.trackURLs(impression.notViewable, macros); + }); + } + + /** + * Tracks ViewUndetermined impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackUndeterminedImpression", + value: function trackUndeterminedImpression() { + var _this5 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this5.trackURLs(impression.viewUndetermined, macros); + }); + } + /** * Send a request to the URI provided by the VAST element. * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code. */ - }, { key: "error", value: function error() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var isCustomCode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (_typeof(macros) !== 'object' || typeof isCustomCode !== 'boolean') { return; } - this.trackURLs(this.ad.errorURLTemplates, macros, { isCustomCode: isCustomCode }); } + /** * Send a request to the URI provided by the VAST element. * If an [ERRORCODE] macro is included, it will be substitute with errorCode. @@ -3972,22 +3701,20 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {String} errorCode - Replaces [ERRORCODE] macro. [ERRORCODE] values are listed in the VAST specification. * @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code. */ - }, { key: "errorWithCode", value: function errorWithCode(errorCode) { var isCustomCode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (typeof errorCode !== 'string' || typeof isCustomCode !== 'boolean') { return; } - this.error({ ERRORCODE: errorCode - }, isCustomCode); //eslint-disable-next-line - + }, isCustomCode); + //eslint-disable-next-line console.log('The method errorWithCode is deprecated, please use vast tracker error method instead'); } + /** * Must be called when the user watched the linear creative until its end. * Calls the complete tracking URLs. @@ -3995,20 +3722,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#complete */ - }, { key: "complete", value: function complete() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('complete', { macros: macros }); } + /** * Must be called if the ad was not and will not be played * This is a terminal event; no other tracking events should be sent when this is used. @@ -4017,21 +3742,19 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#notUsed */ - }, { key: "notUsed", value: function notUsed() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('notUsed', { macros: macros }); this.trackingEvents = []; } + /** * An optional metric that can capture all other user interactions * under one metric such as hover-overs, or custom clicks. It should NOT replace @@ -4041,20 +3764,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#otherAdInteraction */ - }, { key: "otherAdInteraction", value: function otherAdInteraction() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('otherAdInteraction', { macros: macros }); } + /** * Must be called if the user clicked or otherwise activated a control used to * pause streaming content,* which either expands the ad within the player’s @@ -4065,20 +3786,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#acceptInvitation */ - }, { key: "acceptInvitation", value: function acceptInvitation() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('acceptInvitation', { macros: macros }); } + /** * Must be called if user activated a control to expand the creative. * Calls the adExpand tracking URLs. @@ -4086,20 +3805,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#adExpand */ - }, { key: "adExpand", value: function adExpand() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('adExpand', { macros: macros }); } + /** * Must be called when the user activated a control to reduce the creative to its original dimensions. * Calls the adCollapse tracking URLs. @@ -4107,20 +3824,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#adCollapse */ - }, { key: "adCollapse", value: function adCollapse() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('adCollapse', { macros: macros }); } + /** * Must be called if the user clicked or otherwise activated a control used to minimize the ad. * Calls the minimize tracking URLs. @@ -4128,20 +3843,18 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#minimize */ - }, { key: "minimize", value: function minimize() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('minimize', { macros: macros }); } + /** * Must be called if the player did not or was not able to execute the provided * verification code.The [REASON] macro must be filled with reason code @@ -4151,34 +3864,26 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#verificationNotExecuted */ - }, { key: "verificationNotExecuted", value: function verificationNotExecuted(vendor) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof vendor !== 'string' || _typeof(macros) !== 'object') { return; } - if (!this.ad || !this.ad.adVerifications || !this.ad.adVerifications.length) { throw new Error('No adVerifications provided'); } - if (!vendor) { throw new Error('No vendor provided, unable to find associated verificationNotExecuted'); } - var vendorVerification = this.ad.adVerifications.find(function (verifications) { return verifications.vendor === vendor; }); - if (!vendorVerification) { throw new Error("No associated verification element found for vendor: ".concat(vendor)); } - var vendorTracking = vendorVerification.trackingEvents; - if (vendorTracking && vendorTracking.verificationNotExecuted) { var verifsNotExecuted = vendorTracking.verificationNotExecuted; this.trackURLs(verifsNotExecuted, macros); @@ -4187,6 +3892,7 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { }); } } + /** * The time that the initial ad is displayed. This time is based on * the time between the impression and either the completed length of display based @@ -4199,21 +3905,19 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#overlayViewDuration */ - }, { key: "overlayViewDuration", value: function overlayViewDuration(formattedDuration) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof formattedDuration !== 'string' || _typeof(macros) !== 'object') { return; } - macros['ADPLAYHEAD'] = formattedDuration; this.track('overlayViewDuration', { macros: macros }); } + /** * Must be called when the player or the window is closed during the ad. * Calls the `closeLinear` (in VAST 3.0 and 4.1) and `close` tracking URLs. @@ -4222,40 +3926,36 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @emits VASTTracker#closeLinear * @emits VASTTracker#close */ - }, { key: "close", value: function close() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track(this.linear ? 'closeLinear' : 'close', { macros: macros }); } + /** * Must be called when the skip button is clicked. Calls the skip tracking URLs. * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * * @emits VASTTracker#skip */ - }, { key: "skip", value: function skip() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('skip', { macros: macros }); } + /** * Must be called then loaded and buffered the creative’s media and assets either fully * or to the extent that it is ready to play the media @@ -4264,89 +3964,79 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * * @emits VASTTracker#loaded */ - }, { key: "load", value: function load() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('loaded', { macros: macros }); } + /** * Must be called when the user clicks on the creative. * It calls the tracking URLs and emits a 'clickthrough' event with the resolved * clickthrough URL when done. * - * @param {String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback + * @param {?String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#clickthrough */ - }, { key: "click", value: function click() { var fallbackClickThroughURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (fallbackClickThroughURL !== null && typeof fallbackClickThroughURL !== 'string' || _typeof(macros) !== 'object') { return; } - if (this.clickTrackingURLTemplates && this.clickTrackingURLTemplates.length) { this.trackURLs(this.clickTrackingURLTemplates, macros); - } // Use the provided fallbackClickThroughURL as a fallback - - - var clickThroughURLTemplate = this.clickThroughURLTemplate || fallbackClickThroughURL; // clone second usage of macros, which get mutated inside resolveURLTemplates + } + // Use the provided fallbackClickThroughURL as a fallback + var clickThroughURLTemplate = this.clickThroughURLTemplate || fallbackClickThroughURL; + // clone second usage of macros, which get mutated inside resolveURLTemplates var clonedMacros = _objectSpread2({}, macros); - if (clickThroughURLTemplate) { if (this.progress) { clonedMacros['ADPLAYHEAD'] = this.progressFormatted(); } - var clickThroughURL = util.resolveURLTemplates([clickThroughURLTemplate], clonedMacros)[0]; this.emit('clickthrough', clickThroughURL); } } + /** * Calls the tracking URLs for the given eventName and emits the event. * * @param {String} eventName - The name of the event. - * @param {Object} [macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls. - * @param {Boolean} [once=false] - Boolean to define if the event has to be tracked only once. + * @param {Object} options + * @param {Object} [options.macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls. + * @param {Boolean} [options.once=false] - Boolean to define if the event has to be tracked only once. * */ - }, { key: "track", value: function track(eventName) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$macros = _ref.macros, - macros = _ref$macros === void 0 ? {} : _ref$macros, - _ref$once = _ref.once, - once = _ref$once === void 0 ? false : _ref$once; - + _ref$macros = _ref.macros, + macros = _ref$macros === void 0 ? {} : _ref$macros, + _ref$once = _ref.once, + once = _ref$once === void 0 ? false : _ref$once; if (_typeof(macros) !== 'object') { return; - } // closeLinear event was introduced in VAST 3.0 + } + // closeLinear event was introduced in VAST 3.0 // Fallback to vast 2.0 close event if necessary - - if (eventName === 'closeLinear' && !this.trackingEvents[eventName] && this.trackingEvents['close']) { eventName = 'close'; } - var trackingURLTemplates = this.trackingEvents[eventName]; var isAlwaysEmitEvent = this.emitAlwaysEvents.indexOf(eventName) > -1; - if (trackingURLTemplates) { this.emit(eventName, { trackingURLTemplates: trackingURLTemplates @@ -4355,15 +4045,14 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { } else if (isAlwaysEmitEvent) { this.emit(eventName, null); } - if (once) { delete this.trackingEvents[eventName]; - if (isAlwaysEmitEvent) { this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(eventName), 1); } } } + /** * Calls the tracking urls templates with the given macros . * @@ -4371,74 +4060,62 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { * @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. */ - }, { key: "trackURLs", value: function trackURLs(URLTemplates) { - var _this$creative, _this$creative$univer; - + var _this$creative; var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - + var validUrlTemplates = util.filterValidUrlTemplates(URLTemplates); //Avoid mutating the object received in parameters. var givenMacros = _objectSpread2({}, macros); - if (this.linear) { if (this.creative && this.creative.mediaFiles && this.creative.mediaFiles[0] && this.creative.mediaFiles[0].fileURL) { givenMacros['ASSETURI'] = this.creative.mediaFiles[0].fileURL; } - if (this.progress) { givenMacros['ADPLAYHEAD'] = this.progressFormatted(); } } - - if ((_this$creative = this.creative) !== null && _this$creative !== void 0 && (_this$creative$univer = _this$creative.universalAdIds) !== null && _this$creative$univer !== void 0 && _this$creative$univer.length) { + if ((_this$creative = this.creative) !== null && _this$creative !== void 0 && (_this$creative = _this$creative.universalAdIds) !== null && _this$creative !== void 0 && _this$creative.length) { givenMacros['UNIVERSALADID'] = this.creative.universalAdIds.map(function (universalAdId) { return universalAdId.idRegistry.concat(' ', universalAdId.value); }).join(','); } - if (this.ad) { if (this.ad.sequence) { givenMacros['PODSEQUENCE'] = this.ad.sequence; } - if (this.ad.adType) { givenMacros['ADTYPE'] = this.ad.adType; } - if (this.ad.adServingId) { givenMacros['ADSERVINGID'] = this.ad.adServingId; } - if (this.ad.categories && this.ad.categories.length) { givenMacros['ADCATEGORIES'] = this.ad.categories.map(function (category) { return category.value; }).join(','); } - if (this.ad.blockedAdCategories && this.ad.blockedAdCategories.length) { givenMacros['BLOCKEDADCATEGORIES'] = this.ad.blockedAdCategories; } } - - util.track(URLTemplates, givenMacros, options); + util.track(validUrlTemplates, givenMacros, options); } + /** * Formats time in seconds to VAST timecode (e.g. 00:00:10.000) * * @param {Number} timeInSeconds - Number in seconds * @return {String} */ - }, { key: "convertToTimecode", value: function convertToTimecode(timeInSeconds) { if (!util.isValidTimeValue(timeInSeconds)) { return ''; } - var progress = timeInSeconds * 1000; var hours = Math.floor(progress / (60 * 60 * 1000)); var minutes = Math.floor(progress / (60 * 1000) % 60); @@ -4446,22 +4123,22 @@ var VASTTracker = /*#__PURE__*/function (_EventEmitter) { var milliseconds = Math.floor(progress % 1000); return "".concat(util.addLeadingZeros(hours, 2), ":").concat(util.addLeadingZeros(minutes, 2), ":").concat(util.addLeadingZeros(seconds, 2), ".").concat(util.addLeadingZeros(milliseconds, 3)); } + /** * Formats time progress in a readable string. * * @return {String} */ - }, { key: "progressFormatted", value: function progressFormatted() { return this.convertToTimecode(this.progress); } }]); - return VASTTracker; }(EventEmitter); exports.VASTClient = VASTClient; exports.VASTParser = VASTParser; exports.VASTTracker = VASTTracker; +exports.parseDuration = parseDuration; diff --git a/dist/vast-client-node.min.js b/dist/vast-client-node.min.js index e9d1fb45..7a878e00 100644 --- a/dist/vast-client-node.min.js +++ b/dist/vast-client-node.min.js @@ -1 +1 @@ -"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function t(t){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}Object.defineProperty(exports,"__esModule",{value:!0});var f=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 m(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=y(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=b(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=R(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(g(s,t))}return i}function g(e,t){var r=(e=T(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return f.indexOf(e)>-1}));return 0===i.length?e:T(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function T(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function y(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function A(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var E={track:function(e,t,r){m(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:m,extractURLsFromTemplates:y,containsTemplateObject:A,isTemplateObjectEqual:k,encodeURIComponentRFC3986:R,replaceUrlMacros:g,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[],n=r.concat(i);return n.reduce((function(e,t){return A(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:b};function N(e){return-1!==["true","TRUE","True","1"].indexOf(e)}var L={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:N,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i3600||i>60?-1:a+n+i},splitVAST:function(e){var t=[],r=null;return e.forEach((function(i,n){if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=N(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(p(e.viewableImpression),p(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var r=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),i=r.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){E.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=r.concat(e.creatives);var n=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,a=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var o=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(o)}"linear"===e.type&&(n&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),a&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&i.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=E.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,i)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories))}};function w(e,t){var r=function(){var e=v(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=L.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotID:e.adSlotID||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,xmlEncoded:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(L.parseAttributes(e));t.htmlResources=L.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=L.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=L.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=L.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=L.childrenByName(e,"StaticResource").reduce((function(e,t){var r=L.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=L.parseNodeText(L.childByName(e,"AltText"))||null;var r=L.childByName(e,"TrackingEvents");r&&L.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=L.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=L.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:L.parseNodeText(e)}})),t.companionClickThroughURLTemplate=L.parseNodeText(L.childByName(e,"CompanionClickThrough"))||null;var i=L.childByName(e,"AdParameters");return i&&(t.adParameters=L.parseNodeText(i),t.xmlEncoded=i.getAttribute("xmlEncoded")||null),t})),r}function U(e){return"linear"===e.type}function C(e,t){var r,i=function(){var e=v(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=L.parseDuration(L.parseNodeText(L.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=L.parseDuration(n);var o=L.childByName(e,"VideoClicks");if(o){var s=L.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:L.parseNodeText(s)}:null,L.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:L.parseNodeText(e)})})),L.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:L.parseNodeText(e)})}))}var l=L.childByName(e,"AdParameters");l&&(i.adParameters=L.parseNodeText(l)),L.childrenByName(e,"TrackingEvents").forEach((function(e){L.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=L.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(L.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),L.childrenByName(e,"MediaFiles").forEach((function(e){L.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=L.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=L.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=L.parseBoolean(i));return t}(e))}));var t=L.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:L.parseBoolean(e.variableDuration),fileURL:null}}(L.parseAttributes(e));return t.fileURL=L.parseNodeText(e),t}(t));var r=L.childByName(e,"ClosedCaptionFiles");r&&L.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(L.parseAttributes(e));t.fileURL=L.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=L.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var u={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};u.id=s.getAttribute("id"),u.fileURL=L.parseNodeText(s),u.delivery=l.delivery,u.codec=s.getAttribute("codec"),u.type=l.type,u.width=parseInt(l.width,10),u.height=parseInt(l.height,10),u.fileSize=parseInt(s.getAttribute("fileSize"),10),u.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=u}}));var u=L.childByName(e,"Icons");return u&&L.childrenByName(u,"Icon").forEach((function(e){i.icons.push(function(e){var t={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};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=L.parseDuration(e.getAttribute("offset")),t.duration=L.parseDuration(e.getAttribute("duration")),L.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=L.parseNodeText(e)})),L.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=L.parseNodeText(e)})),L.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=L.parseNodeText(e)}));var r=L.childByName(e,"IconClicks");r&&(t.iconClickThroughURLTemplate=L.parseNodeText(L.childByName(r,"IconClickThrough")),L.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:L.parseNodeText(e)})})));return t.iconViewTrackingURLTemplate=L.parseNodeText(L.childByName(e,"IconViewTracking")),t}(e))})),i}function I(e,t){var r=function(){var e=v(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return L.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;L.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=L.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),L.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=L.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=L.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=L.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),L.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=L.parseNodeText(e)})),L.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=L.parseNodeText(e)})),L.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=L.parseNodeText(e)}));var i=L.childByName(e,"AdParameters");i&&(t.adParameters=L.parseNodeText(i)),t.nonlinearClickThroughURLTemplate=L.parseNodeText(L.childByName(e,"NonLinearClickThrough")),L.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:L.parseNodeText(e)})})),r.variations.push(t)})),r}function x(e){var t=[];return e.forEach((function(e){var r=S(e);r&&t.push(r)})),t}function S(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=S(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var u=L.parseNodeText(e);""!==u&&(r.value=u),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function O(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:D(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];L.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:L.parseNodeText(e)};n.push(t)}));var a=L.childByName(e,"CreativeExtensions");for(var o in a&&(r=x(L.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=C(s,i);break;case"NonLinearAds":l=I(s,i);break;case"CompanionAds":l=w(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function D(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var V={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function P(e,t){if(V[e.nodeName]&&V[e.nodeName].attributes){var r=V[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&M({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function B(e,t,r){var i=V[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!L.childByName(e,t)}));a.length>0&&M({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return L.childByName(e,t)}))||M({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function F(e){return e.children&&0!==e.children.length}function M(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var j={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),P(t,r),F(t)){B(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(L.copyNodeAttribute("id",e,s),L.copyNodeAttribute("sequence",e,s),L.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:_(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:q(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function q(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds;return!1===i&&e.getAttribute("sequence")?null:H(e,t)}function H(e,t){var r=[];t&&j.verifyRequiredValues(e,t);var i=e.childNodes,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(L.parseAttributes(e));for(var a in i){var o=i[a];switch(o.nodeName){case"Error":n.errorURLTemplates.push(L.parseNodeText(o));break;case"Impression":n.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:L.parseNodeText(o)});break;case"Creatives":n.creatives=O(L.childrenByName(o,"Creative"));break;case"Extensions":var s=L.childrenByName(o,"Extension");n.extensions=x(s),n.adVerifications.length||(r=z(s));break;case"AdVerifications":n.adVerifications=G(L.childrenByName(o,"Verification"));break;case"AdSystem":n.system={value:L.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":n.title=L.parseNodeText(o);break;case"AdServingId":n.adServingId=L.parseNodeText(o);break;case"Category":n.categories.push({authority:o.getAttribute("authority")||null,value:L.parseNodeText(o)});break;case"Expires":n.expires=parseInt(L.parseNodeText(o),10);break;case"ViewableImpression":n.viewableImpression.push(Y(o));break;case"Description":n.description=L.parseNodeText(o);break;case"Advertiser":n.advertiser={id:o.getAttribute("id")||null,value:L.parseNodeText(o)};break;case"Pricing":n.pricing={value:L.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":n.survey=L.parseNodeText(o);break;case"BlockedAdCategories":n.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:L.parseNodeText(o)})}}return r.length&&(n.adVerifications=n.adVerifications.concat(r)),n}function _(e,t){var r=H(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||L.parseBoolean(i),r.allowMultipleAds=!!n&&L.parseBoolean(n),r.fallbackOnNoAd=a?L.parseBoolean(a):null;var o=L.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=L.parseNodeText(o):(o=L.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=L.parseNodeText(L.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function G(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in L.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=L.parseNodeText(a),L.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=L.parseNodeText(a)}}var o=L.childByName(e,"TrackingEvents");o&&L.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=L.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function z(e){var t=null,r=[];return e.some((function(e){return t=L.childByName(e,"AdVerifications")})),t&&(r=G(L.childrenByName(t,"Verification"))),r}function Y(e){var t={};t.id=e.getAttribute("id")||null;var r=e.childNodes;for(var i in r){var n=r[i],a=n.nodeName,o=L.parseNodeText(n);if(("Viewable"===a||"NotViewable"===a||"ViewUndetermined"===a)&&o){var s=a.toLowerCase();Array.isArray(t[s])||(t[s]=[]),t[s].push(o)}}return t}var X=function(){function e(){i(this,e),this._handlers=[]}return a(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(r(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(r(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)})),t.parentURLs.push(e);var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},c=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:c},u);t.emit("VAST-resolved",d),se(u.byteLength,c),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||12e4,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parentURLs=[],this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||ne,this.vastVersion=null,se(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?E.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.parentURLs=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,u=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var c=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=L.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&c.length>1)break;var m=W(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:u});m.ad?(c.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:c.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,u=void 0===l?null:l,c=t.wrapperDepth,d=void 0===c?0:c,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=L.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:u,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=E.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth||-1!==i.parentURLs.indexOf(e.nextWrapperURL))return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=L.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&L.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(),ce=null,de={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},pe=function(){function e(){i(this,e),this.storage=this.initStorage()}return a(e,[{key:"initStorage",value:function(){if(ce)return ce;try{ce="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){ce=null}return ce&&!this.isStorageDisabled(ce)||(ce=de).clear(),ce}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),he=function(){function e(t,r,n){i(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new ue,this.storage=n||new pe,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return a(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null;for(var l in i(this,o),(a=n.call(this)).ad=t,a.creative=r,a.variation=s,a.muted=!1,a.impressed=!1,a.skippable=!1,a.trackingEvents={},a.lastPercentage=0,a._alreadyTriggeredQuartiles={},a.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],a.creative.trackingEvents){var u=a.creative.trackingEvents[l];a.trackingEvents[l]=u.slice(0)}return U(a.creative)?a._initLinearTracking():a._initVariationTracking(),e&&a.on("start",(function(){e.lastSuccessfulAd=Date.now()})),a}return a(o,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){E.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(E.isValidTimeValue(e)&&"object"===r(i)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){E.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===r(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===r(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var i=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!i)throw new Error("No associated verification element found for vendor: ".concat(e));var n=i.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===r(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===r(i)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,i);var n=this.clickThroughURLTemplate||e,a=t({},i);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=E.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.macros,n=void 0===i?{}:i,a=t.once,o=void 0!==a&&a;if("object"===r(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var r,i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=t({},n);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(r=this.creative)&&void 0!==r&&null!==(i=r.universalAdIds)&&void 0!==i&&i.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),E.track(e,o,a)}},{key:"convertToTimecode",value:function(e){if(!E.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(E.addLeadingZeros(r,2),":").concat(E.addLeadingZeros(i,2),":").concat(E.addLeadingZeros(n,2),".").concat(E.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),o}();exports.VASTClient=he,exports.VASTParser=ue,exports.VASTTracker=ve; +"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function t(t){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}Object.defineProperty(exports,"__esModule",{value:!0});var m=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 g(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=k(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=N(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=E(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(y(s,t))}return i}function y(e,t){var r=(e=T(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return m.indexOf(e)>-1}));return 0===i.length?e:T(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function T(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function k(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function A(e){return/^(https?:\/\/|\/\/)/.test(e)}function b(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var L={track:function(e,t,r){g(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:g,extractURLsFromTemplates:k,filterValidUrlTemplates:function(e){return Array.isArray(e)?e.filter((function(e){return A(e.hasOwnProperty("url")?e.url:e)})):A(e)},containsTemplateObject:b,isTemplateObjectEqual:R,encodeURIComponentRFC3986:E,replaceUrlMacros:y,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce((function(e,t){return b(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:N};function w(e){return-1!==["true","TRUE","True","1"].indexOf(e)}function U(e){if(null==e)return-1;if(L.isNumeric(e))return parseInt(e);var t=e.split(":");if(3!==t.length)return-1;var r=t[2].split("."),i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));var n=parseInt(60*t[1]),a=parseInt(60*t[0]*60);return isNaN(a)||isNaN(n)||isNaN(i)||n>3600||i>60?-1:a+n+i}var C={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:w,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=w(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(p(e.viewableImpression),p(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var i=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),n=i.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){L.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=i.concat(e.creatives);var a=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,o=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(a&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),o&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&n.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=L.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,n)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){var s=t.creatives.filter((function(e){var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));s.length&&(e.creatives=e.creatives.concat(s))}}};function I(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=C.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(C.parseAttributes(e));t.htmlResources=C.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=C.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=C.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=C.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=C.childrenByName(e,"StaticResource").reduce((function(e,t){var r=C.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=C.parseNodeText(C.childByName(e,"AltText"))||null;var r=C.childByName(e,"TrackingEvents");r&&C.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=C.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=C.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:C.parseNodeText(e)}})),t.companionClickThroughURLTemplate=C.parseNodeText(C.childByName(e,"CompanionClickThrough"))||null;var i=C.childByName(e,"AdParameters");return i&&(t.adParameters={value:C.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),r}function x(e,t){var r,i=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=C.parseDuration(C.parseNodeText(C.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=C.parseDuration(n);var o=C.childByName(e,"VideoClicks");if(o){var s=C.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:C.parseNodeText(s)}:null,C.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:C.parseNodeText(e)})})),C.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:C.parseNodeText(e)})}))}var l=C.childByName(e,"AdParameters");l&&(i.adParameters={value:C.parseNodeText(l),xmlEncoded:l.getAttribute("xmlEncoded")||null}),C.childrenByName(e,"TrackingEvents").forEach((function(e){C.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=C.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(C.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),C.childrenByName(e,"MediaFiles").forEach((function(e){C.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=C.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=C.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=C.parseBoolean(i));return t}(e))}));var t=C.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:C.parseBoolean(e.variableDuration),fileURL:null}}(C.parseAttributes(e));return t.fileURL=C.parseNodeText(e),t}(t));var r=C.childByName(e,"ClosedCaptionFiles");r&&C.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(C.parseAttributes(e));t.fileURL=C.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=C.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var u={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};u.id=s.getAttribute("id"),u.fileURL=C.parseNodeText(s),u.delivery=l.delivery,u.codec=s.getAttribute("codec"),u.type=l.type,u.width=parseInt(l.width,10),u.height=parseInt(l.height,10),u.fileSize=parseInt(s.getAttribute("fileSize"),10),u.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=u}}));var u=C.childByName(e,"Icons");return u&&C.childrenByName(u,"Icon").forEach((function(e){i.icons.push(function(e){var t={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:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=C.parseDuration(e.getAttribute("offset")),t.duration=C.parseDuration(e.getAttribute("duration")),C.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=C.parseNodeText(e)})),C.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=C.parseNodeText(e)})),C.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=C.parseNodeText(e)}));var r=C.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=C.parseNodeText(C.childByName(r,"IconClickThrough")),C.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:C.parseNodeText(e)})}));var i=C.childByName(r,"IconClickFallbackImages");i&&C.childrenByName(i,"IconClickFallbackImage").forEach((function(e){t.iconClickFallbackImages.push({url:C.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=C.parseNodeText(C.childByName(e,"IconViewTracking")),t}(e))})),i}function S(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return C.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;C.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=C.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),C.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=C.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=C.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=C.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),C.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=C.parseNodeText(e)})),C.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=C.parseNodeText(e)})),C.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=C.parseNodeText(e)}));var i=C.childByName(e,"AdParameters");i&&(t.adParameters={value:C.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=C.parseNodeText(C.childByName(e,"NonLinearClickThrough")),C.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:C.parseNodeText(e)})})),r.variations.push(t)})),r}function O(e){var t=[];return e.forEach((function(e){var r=D(e);r&&t.push(r)})),t}function D(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=D(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var u=C.parseNodeText(e);""!==u&&(r.value=u),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function V(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:P(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];C.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:C.parseNodeText(e)};n.push(t)}));var a=C.childByName(e,"CreativeExtensions");for(var o in a&&(r=O(C.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=x(s,i);break;case"NonLinearAds":l=S(s,i);break;case"CompanionAds":l=I(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function P(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var B={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function F(e,t){if(B[e.nodeName]&&B[e.nodeName].attributes){var r=B[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&W({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function M(e,t,r){var i=B[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!C.childByName(e,t)}));a.length>0&&W({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return C.childByName(e,t)}))||W({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function j(e){return e.children&&0!==e.children.length}function W(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var q={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),F(t,r),j(t)){M(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(C.copyNodeAttribute("id",e,s),C.copyNodeAttribute("sequence",e,s),C.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:z(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:_(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function _(e,t){return!1===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allowMultipleAds&&e.getAttribute("sequence")?null:G(e,t)}function G(e,t){var r=[];t&&q.verifyRequiredValues(e,t);var i,n,a=e.childNodes,o=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(C.parseAttributes(e));for(var s in a){var l=a[s];switch(l.nodeName){case"Error":o.errorURLTemplates.push(C.parseNodeText(l));break;case"Impression":o.impressionURLTemplates.push({id:l.getAttribute("id")||null,url:C.parseNodeText(l)});break;case"Creatives":o.creatives=V(C.childrenByName(l,"Creative"));break;case"Extensions":var u=C.childrenByName(l,"Extension");o.extensions=O(u),o.adVerifications.length||(r=X(u));break;case"AdVerifications":o.adVerifications=Y(C.childrenByName(l,"Verification"));break;case"AdSystem":o.system={value:C.parseNodeText(l),version:l.getAttribute("version")||null};break;case"AdTitle":o.title=C.parseNodeText(l);break;case"AdServingId":o.adServingId=C.parseNodeText(l);break;case"Category":o.categories.push({authority:l.getAttribute("authority")||null,value:C.parseNodeText(l)});break;case"Expires":o.expires=parseInt(C.parseNodeText(l),10);break;case"ViewableImpression":o.viewableImpression.push((n=void 0,n=function(e,t){var r=C.parseNodeText(t);return r&&e.push(r),e},{id:(i=l).getAttribute("id")||null,viewable:C.childrenByName(i,"Viewable").reduce(n,[]),notViewable:C.childrenByName(i,"NotViewable").reduce(n,[]),viewUndetermined:C.childrenByName(i,"ViewUndetermined").reduce(n,[])}));break;case"Description":o.description=C.parseNodeText(l);break;case"Advertiser":o.advertiser={id:l.getAttribute("id")||null,value:C.parseNodeText(l)};break;case"Pricing":o.pricing={value:C.parseNodeText(l),model:l.getAttribute("model")||null,currency:l.getAttribute("currency")||null};break;case"Survey":o.survey={value:C.parseNodeText(l),type:l.getAttribute("type")||null};break;case"BlockedAdCategories":o.blockedAdCategories.push({authority:l.getAttribute("authority")||null,value:C.parseNodeText(l)})}}return r.length&&(o.adVerifications=o.adVerifications.concat(r)),o}function z(e,t){var r=G(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||C.parseBoolean(i),r.allowMultipleAds=!!n&&C.parseBoolean(n),r.fallbackOnNoAd=a?C.parseBoolean(a):null;var o=C.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=C.parseNodeText(o):(o=C.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=C.parseNodeText(C.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function Y(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in C.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=C.parseNodeText(a),C.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=C.parseNodeText(a)}}var o=C.childByName(e,"TrackingEvents");o&&C.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=C.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function X(e){var t=null,r=[];return e.some((function(e){return t=C.childByName(e,"AdVerifications")})),t&&(r=Y(C.childrenByName(t,"Verification"))),r}var K=function(){function e(){i(this,e),this._handlers=[]}return a(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(r(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(r(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)}));var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},c=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:c},u);t.emit("VAST-resolved",d),ue(u.byteLength,c),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||Q,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||oe,this.vastVersion=null,ue(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?L.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,u=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var c=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=C.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&c.length>1)break;var m=H(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:u});m.ad?(c.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:c.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,u=void 0===l?null:l,c=t.wrapperDepth,d=void 0===c?0:c,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=C.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:u,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=L.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth)return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=C.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&C.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(),pe=null,he={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},ve=function(){function e(){i(this,e),this.storage=this.initStorage()}return a(e,[{key:"initStorage",value:function(){if(pe)return pe;try{pe="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){pe=null}return pe&&!this.isStorageDisabled(pe)||(pe=he).clear(),pe}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),fe=function(){function e(t,r,n){i(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new de,this.storage=n||new ve,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return a(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null,l=arguments.length>4&&void 0!==arguments[4]&&arguments[4];for(var u in i(this,o),(a=n.call(this)).ad=t,a.creative=r,a.variation=s,a.muted=l,a.impressed=!1,a.skippable=!1,a.trackingEvents={},a.lastPercentage=0,a._alreadyTriggeredQuartiles={},a.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],a.creative.trackingEvents){var c=a.creative.trackingEvents[u];a.trackingEvents[u]=c.slice(0)}return!function(e){return"linear"===e.type}(a.creative)?a._initVariationTracking():a._initLinearTracking(),e&&a.on("start",(function(){e.lastSuccessfulAd=Date.now()})),a}return a(o,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){L.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(L.isValidTimeValue(e)&&"object"===r(i)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===r(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){L.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"trackViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewable,t)}))}},{key:"trackNotViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.notViewable,t)}))}},{key:"trackUndeterminedImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewUndetermined,t)}))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===r(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===r(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var i=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!i)throw new Error("No associated verification element found for vendor: ".concat(e));var n=i.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===r(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===r(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===r(i)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,i);var n=this.clickThroughURLTemplate||e,a=t({},i);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=L.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.macros,n=void 0===i?{}:i,a=t.once,o=void 0!==a&&a;if("object"===r(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=L.filterValidUrlTemplates(e),o=t({},i);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(r=this.creative)&&void 0!==r&&null!==(r=r.universalAdIds)&&void 0!==r&&r.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),L.track(a,o,n)}},{key:"convertToTimecode",value:function(e){if(!L.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(L.addLeadingZeros(r,2),":").concat(L.addLeadingZeros(i,2),":").concat(L.addLeadingZeros(n,2),".").concat(L.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),o}();exports.VASTClient=fe,exports.VASTParser=de,exports.VASTTracker=me,exports.parseDuration=U; diff --git a/dist/vast-client.js b/dist/vast-client.js index dcff6b30..2a572fc2 100644 --- a/dist/vast-client.js +++ b/dist/vast-client.js @@ -6,17 +6,14 @@ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } - return keys; } - function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; @@ -26,10 +23,8 @@ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } - return target; } - function _typeof(obj) { "@babel/helpers - typeof"; @@ -39,23 +34,20 @@ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); @@ -64,8 +56,8 @@ }); return Constructor; } - function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -76,15 +68,12 @@ } else { obj[key] = value; } - return obj; } - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, @@ -97,28 +86,23 @@ }); if (superClass) _setPrototypeOf(subClass, superClass); } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; - return _setPrototypeOf(o, p); } - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; - try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; @@ -126,56 +110,43 @@ return false; } } - function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return self; } - function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } - return _assertThisInitialized(self); } - function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), - result; - + result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } - return _possibleConstructorReturn(this, result); }; } - function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); @@ -184,18 +155,28 @@ if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; } - function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } function createAd() { var adAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; @@ -250,14 +231,13 @@ expandedWidth: creativeAttributes.expandedWidth || null, expandedHeight: creativeAttributes.expandedHeight || null, apiFramework: creativeAttributes.apiFramework || null, - adSlotID: creativeAttributes.adSlotID || null, + adSlotId: creativeAttributes.adSlotId || null, pxratio: creativeAttributes.pxratio || '1', renderingMode: creativeAttributes.renderingMode || 'default', staticResources: [], htmlResources: [], iframeResources: [], adParameters: null, - xmlEncoded: null, altText: null, companionClickThroughURLTemplate: null, companionClickTrackingURLTemplates: [], @@ -282,13 +262,11 @@ function createCreativeCompanion() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -300,7 +278,8 @@ }; } - var 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 + var 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) { @@ -312,6 +291,7 @@ } }); } + /** * Replace the provided URLTemplates with the given values * @@ -319,40 +299,36 @@ * @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) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var resolvedURLs = []; - var URLArray = extractURLsFromTemplates(URLTemplates); // Set default value for invalid ERRORCODE + var 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 - + } + // 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['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 (var macro in macros) { macros[macro] = encodeURIComponentRFC3986(macros[macro]); } - for (var URLTemplateKey in URLArray) { var 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, @@ -361,50 +337,42 @@ * @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 - + url = replaceMacrosValues(url, macros); + // match any macros from the url that was not replaced var remainingMacros = url.match(/[^[\]]+(?=])/g); - if (!remainingMacros) { return url; } - var supportedRemainingMacros = remainingMacros.filter(function (macro) { return supportedMacros.indexOf(macro) > -1; }); - if (supportedRemainingMacros.length === 0) { return url; } - supportedRemainingMacros = supportedRemainingMacros.reduce(function (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) { var replacedMacrosUrl = url; - for (var key in macros) { - var value = macros[key]; // this will match [${key}] and %%${key}%% and replace it - + var 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 @@ -413,17 +381,38 @@ * * @param {Array|String} URLTemplates - An array|string of url templates. */ - - function extractURLsFromTemplates(URLTemplates) { if (Array.isArray(URLTemplates)) { return URLTemplates.map(function (URLTemplate) { return URLTemplate && URLTemplate.hasOwnProperty('url') ? URLTemplate.url : URLTemplate; }); } - return URLTemplates; } + + /** + * Filter URLTemplates elements to keep only valid and safe URL templates. + * To be valid, urls should: + * - have the same protocol as the client + * or + * - be protocol-relative urls + * + * @param {Array} URLTemplates - A Array of string/object containing urls templates. + */ + function filterValidUrlTemplates(URLTemplates) { + if (Array.isArray(URLTemplates)) { + return URLTemplates.filter(function (urlTemplate) { + var url = urlTemplate.hasOwnProperty('url') ? urlTemplate.url : urlTemplate; + return isValidUrl(url); + }); + } + return isValidUrl(URLTemplates); + } + function isValidUrl(url) { + var 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 @@ -431,17 +420,15 @@ * @param {Object} obj - The object who existence is to be checked. * @param {Array} list - List of objects. */ - - function containsTemplateObject(obj, list) { for (var 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 @@ -449,33 +436,30 @@ * @param {Object} obj1 * @param {Object} obj2 */ - - function isTemplateObjectEqual(obj1, obj2) { if (obj1 && obj2) { var obj1Properties = Object.getOwnPropertyNames(obj1); - var obj2Properties = Object.getOwnPropertyNames(obj2); // If number of properties is different, objects are not equivalent + var 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 - + } + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent function encodeURIComponentRFC3986(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return "%".concat(c.charCodeAt(0).toString(16)); }); } + /** * Return a string of the input number with leading zeros defined by the length param * @@ -484,22 +468,19 @@ * * @return {String} */ - - function addLeadingZeros(input) { var 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(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); } + /** * Joins two arrays of objects without duplicates * @@ -508,8 +489,6 @@ * * @return {Array} */ - - function joinArrayOfUniqueTemplateObjs() { var arr1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var arr2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; @@ -520,10 +499,10 @@ 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. @@ -532,16 +511,14 @@ * * @return {Boolean} */ - - function isValidTimeValue(time) { return Number.isFinite(time) && time >= -2; } - var util = { track: track, resolveURLTemplates: resolveURLTemplates, extractURLsFromTemplates: extractURLsFromTemplates, + filterValidUrlTemplates: filterValidUrlTemplates, containsTemplateObject: containsTemplateObject, isTemplateObjectEqual: isTemplateObjectEqual, encodeURIComponentRFC3986: encodeURIComponentRFC3986, @@ -563,236 +540,200 @@ * @param {String} name - The name to look for. * @return {Object|undefined} */ - function childByName(node, name) { var childNodes = node.childNodes; - for (var childKey in childNodes) { var child = childNodes[childKey]; - if (child.nodeName === name) { return child; } } } + /** * 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) { var children = []; var childNodes = node.childNodes; - for (var childKey in childNodes) { var child = childNodes[childKey]; - if (child.nodeName === name) { children.push(child); } } - return children; } + /** * 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.indexOf('//') === 0) { var _location = location, - protocol = _location.protocol; + protocol = _location.protocol; return "".concat(protocol).concat(vastAdTagUrl); } - if (vastAdTagUrl.indexOf('://') === -1) { // Resolve relative URLs (mainly for unit testing) var 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'].indexOf(booleanString) !== -1; } + /** * 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) { var 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) { var nodeAttributes = element.attributes; var attributes = {}; - for (var i = 0; i < nodeAttributes.length; i++) { attributes[nodeAttributes[i].nodeName] = nodeAttributes[i].nodeValue; } - return attributes; } + /** * 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 - - + } + // 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); } - var durationComponents = durationString.split(':'); - if (durationComponents.length !== 3) { return -1; } - var secondsAndMS = durationComponents[2].split('.'); var seconds = parseInt(secondsAndMS[0]); - if (secondsAndMS.length === 2) { seconds += parseFloat("0.".concat(secondsAndMS[1])); } - var minutes = parseInt(durationComponents[1] * 60); var 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) { var splittedVAST = []; var lastAdPod = null; ads.forEach(function (ad, i) { if (ad.sequence) { ad.sequence = parseInt(ad.sequence, 10); - } // The current Ad may be the next Ad of an AdPod - - + } + // The current Ad may be the next Ad of an AdPod if (ad.sequence > 1) { - var lastAd = ads[i - 1]; // check if the current Ad is exactly the next one in the AdPod - + var 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 + } + // 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) { for (var attrKey in attributes) { var attribute = attributes[attrKey]; - if (attribute.nodeName && attribute.nodeValue && verificationObject.hasOwnProperty(attribute.nodeName)) { var value = attribute.nodeValue; - if (typeof verificationObject[attribute.nodeName] === 'boolean') { value = parseBoolean(value); } - verificationObject[attribute.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 = [].concat(_toConsumableArray(unwrappedAd.viewableImpression), _toConsumableArray(wrapper.viewableImpression)); - } // values from the child wrapper will be overridden - + } + // values from the child wrapper will be overridden unwrappedAd.followAdditionalWrappers = wrapper.followAdditionalWrappers; unwrappedAd.allowMultipleAds = wrapper.allowMultipleAds; unwrappedAd.fallbackOnNoAd = wrapper.fallbackOnNoAd; @@ -817,50 +758,56 @@ if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) { for (var eventName in wrapper.trackingEvents[creative.type]) { var 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 - + } + // 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 - + } + // 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 - + } + // pass wrapper companion trackers to all companions if (creative.type === 'companion' && wrapperCompanionClickTracking.length) { (creative.variations || []).forEach(function (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 + var wrapperCreativesWithIconsNode = wrapper.creatives.filter(function (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); + } + } + } var parserUtils = { childByName: childByName, childrenByName: childrenByName, @@ -885,7 +832,6 @@ * @param {Object} creativeAttributes - The attributes of the CompanionAd (optional). * @return {Object} creative - The creative object. */ - function parseCreativeCompanion(creativeElement, creativeAttributes) { var creative = createCreativeCompanion(creativeAttributes); creative.required = creativeElement.getAttribute('required') || null; @@ -908,22 +854,18 @@ }, []); companionAd.altText = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'AltText')) || null; var trackingEventsElement = parserUtils.childByName(companionResource, 'TrackingEvents'); - if (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var 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(function (clickTrackingElement) { return { id: clickTrackingElement.getAttribute('id') || null, @@ -932,12 +874,12 @@ }); companionAd.companionClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(companionResource, 'CompanionClickThrough')) || null; var adParametersElement = parserUtils.childByName(companionResource, 'AdParameters'); - if (adParametersElement) { - companionAd.adParameters = parserUtils.parseNodeText(adParametersElement); - companionAd.xmlEncoded = adParametersElement.getAttribute('xmlEncoded') || null; + companionAd.adParameters = { + value: parserUtils.parseNodeText(adParametersElement), + xmlEncoded: adParametersElement.getAttribute('xmlEncoded') || null + }; } - return companionAd; }); return creative; @@ -945,13 +887,11 @@ function createCreativeLinear() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -1002,7 +942,8 @@ pxratio: '1', iconClickThroughURLTemplate: null, iconClickTrackingURLTemplates: [], - iconViewTrackingURLTemplate: null + iconViewTrackingURLTemplate: null, + iconClickFallbackImages: [] }; } @@ -1061,13 +1002,11 @@ * @param {any} creativeAttributes - The attributes of the Linear (optional). * @return {Object} creative - The creativeLinear object. */ - function parseCreativeLinear(creativeElement, creativeAttributes) { var offset; var creative = createCreativeLinear(creativeAttributes); creative.duration = parserUtils.parseDuration(parserUtils.parseNodeText(parserUtils.childByName(creativeElement, 'Duration'))); var skipOffset = creativeElement.getAttribute('skipoffset'); - if (typeof skipOffset === 'undefined' || skipOffset === null) { creative.skipDelay = null; } else if (skipOffset.charAt(skipOffset.length - 1) === '%' && creative.duration !== -1) { @@ -1076,12 +1015,9 @@ } else { creative.skipDelay = parserUtils.parseDuration(skipOffset); } - var videoClicksElement = parserUtils.childByName(creativeElement, 'VideoClicks'); - if (videoClicksElement) { var videoClickThroughElement = parserUtils.childByName(videoClicksElement, 'ClickThrough'); - if (videoClickThroughElement) { creative.videoClickThroughURLTemplate = { id: videoClickThroughElement.getAttribute('id') || null, @@ -1090,7 +1026,6 @@ } else { creative.videoClickThroughURLTemplate = null; } - parserUtils.childrenByName(videoClicksElement, 'ClickTracking').forEach(function (clickTrackingElement) { creative.videoClickTrackingURLTemplates.push({ id: clickTrackingElement.getAttribute('id') || null, @@ -1104,37 +1039,32 @@ }); }); } - var adParamsElement = parserUtils.childByName(creativeElement, 'AdParameters'); - if (adParamsElement) { - creative.adParameters = parserUtils.parseNodeText(adParamsElement); + creative.adParameters = { + value: parserUtils.parseNodeText(adParamsElement), + xmlEncoded: adParamsElement.getAttribute('xmlEncoded') || null + }; } - parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var 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); } }); @@ -1144,13 +1074,10 @@ creative.mediaFiles.push(parseMediaFile(mediaFileElement)); }); var interactiveCreativeElement = parserUtils.childByName(mediaFilesElement, 'InteractiveCreativeFile'); - if (interactiveCreativeElement) { creative.interactiveCreativeFile = parseInteractiveCreativeFile(interactiveCreativeElement); } - var closedCaptionElements = parserUtils.childByName(mediaFilesElement, 'ClosedCaptionFiles'); - if (closedCaptionElements) { parserUtils.childrenByName(closedCaptionElements, 'ClosedCaptionFile').forEach(function (closedCaptionElement) { var closedCaptionFile = createClosedCaptionFile(parserUtils.parseAttributes(closedCaptionElement)); @@ -1158,10 +1085,8 @@ creative.closedCaptionFiles.push(closedCaptionFile); }); } - var mezzanineElement = parserUtils.childByName(mediaFilesElement, 'Mezzanine'); var requiredAttributes = getRequiredAttributes(mezzanineElement, ['delivery', 'type', 'width', 'height']); - if (requiredAttributes) { var mezzanine = createMezzanine(); mezzanine.id = mezzanineElement.getAttribute('id'); @@ -1177,21 +1102,19 @@ } }); var iconsElement = parserUtils.childByName(creativeElement, 'Icons'); - if (iconsElement) { parserUtils.childrenByName(iconsElement, 'Icon').forEach(function (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) { var mediaFile = createMediaFile(); mediaFile.id = mediaFileElement.getAttribute('id'); @@ -1208,38 +1131,32 @@ mediaFile.width = parseInt(mediaFileElement.getAttribute('width') || 0); mediaFile.height = parseInt(mediaFileElement.getAttribute('height') || 0); var scalable = mediaFileElement.getAttribute('scalable'); - if (scalable && typeof scalable === 'string') { mediaFile.scalable = parserUtils.parseBoolean(scalable); } - var 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) { var 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) { var icon = createIcon(); icon.program = iconElement.getAttribute('program'); @@ -1264,7 +1181,6 @@ icon.staticResource = parserUtils.parseNodeText(staticElement); }); var iconClicksElement = parserUtils.childByName(iconElement, 'IconClicks'); - if (iconClicksElement) { icon.iconClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(iconClicksElement, 'IconClickThrough')); parserUtils.childrenByName(iconClicksElement, 'IconClickTracking').forEach(function (iconClickTrackingElement) { @@ -1273,47 +1189,51 @@ url: parserUtils.parseNodeText(iconClickTrackingElement) }); }); + var iconClickFallbackImagesElement = parserUtils.childByName(iconClicksElement, 'IconClickFallbackImages'); + if (iconClickFallbackImagesElement) { + parserUtils.childrenByName(iconClickFallbackImagesElement, 'IconClickFallbackImage').forEach(function (iconClickFallbackImageElement) { + icon.iconClickFallbackImages.push({ + url: parserUtils.parseNodeText(iconClickFallbackImageElement) || null, + width: iconClickFallbackImageElement.getAttribute('width') || null, + height: iconClickFallbackImageElement.getAttribute('height') || null + }); + }); + } } - icon.iconViewTrackingURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(iconElement, 'IconViewTracking')); return icon; } + /** * Parses an horizontal position into a String ('left' or 'right') or into a Number. * @param {String} xPosition - The x position to parse. * @return {String|Number} */ - - function parseXPosition(xPosition) { if (['left', 'right'].indexOf(xPosition) !== -1) { return xPosition; } - return parseInt(xPosition || 0); } + /** * Parses an vertical position into a String ('top' or 'bottom') or into a Number. * @param {String} yPosition - The x position to parse. * @return {String|Number} */ - - function parseYPosition(yPosition) { if (['top', 'bottom'].indexOf(yPosition) !== -1) { return yPosition; } - return parseInt(yPosition || 0); } + /** * Getting required attributes from element * @param {Object} element - DOM element * @param {Array} attributes - list of attributes * @return {Object|null} null if a least one element not present */ - - function getRequiredAttributes(element, attributes) { var values = {}; var error = false; @@ -1329,13 +1249,11 @@ function createCreativeNonLinear() { var creativeAttributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var _createCreative = createCreative(creativeAttributes), - id = _createCreative.id, - adId = _createCreative.adId, - sequence = _createCreative.sequence, - apiFramework = _createCreative.apiFramework; - + id = _createCreative.id, + adId = _createCreative.adId, + sequence = _createCreative.sequence, + apiFramework = _createCreative.apiFramework; return { id: id, adId: adId, @@ -1382,7 +1300,6 @@ * @param {any} creativeAttributes - The attributes of the NonLinear (optional). * @return {Object} creative - The CreativeNonLinear object. */ - function parseCreativeNonLinear(creativeElement, creativeAttributes) { var creative = createCreativeNonLinear(creativeAttributes); parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { @@ -1390,12 +1307,10 @@ parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { eventName = trackingElement.getAttribute('event'); trackingURLTemplate = parserUtils.parseNodeText(trackingElement); - if (eventName && trackingURLTemplate) { if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } - creative.trackingEvents[eventName].push(trackingURLTemplate); } }); @@ -1424,11 +1339,12 @@ nonlinearAd.staticResource = parserUtils.parseNodeText(staticElement); }); var adParamsElement = parserUtils.childByName(nonlinearResource, 'AdParameters'); - if (adParamsElement) { - nonlinearAd.adParameters = parserUtils.parseNodeText(adParamsElement); + nonlinearAd.adParameters = { + value: parserUtils.parseNodeText(adParamsElement), + xmlEncoded: adParamsElement.getAttribute('xmlEncoded') || null + }; } - nonlinearAd.nonlinearClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(nonlinearResource, 'NonLinearClickThrough')); parserUtils.childrenByName(nonlinearResource, 'NonLinearClickTracking').forEach(function (clickTrackingElement) { nonlinearAd.nonlinearClickTrackingURLTemplates.push({ @@ -1459,72 +1375,67 @@ * @param {String} type - The type of extensions to parse.(Ad|Creative) * @return {AdExtension[]|CreativeExtension[]} - The nodes parsed to extensions */ - function parseExtensions(extensions) { var exts = []; extensions.forEach(function (extNode) { var ext = _parseExtension(extNode); - if (ext) { exts.push(ext); } }); return exts; } + /** * Parses an extension child node * @param {Node} extNode - The extension node to parse * @return {AdExtension|CreativeExtension|null} - The node parsed to extension */ - function _parseExtension(extNode) { // Ignore comments if (extNode.nodeName === '#comment') return null; var ext = createExtension(); var extNodeAttrs = extNode.attributes; var childNodes = extNode.childNodes; - ext.name = extNode.nodeName; // Parse attributes + ext.name = extNode.nodeName; + // Parse attributes if (extNode.attributes) { for (var extNodeAttrKey in extNodeAttrs) { if (extNodeAttrs.hasOwnProperty(extNodeAttrKey)) { var extNodeAttr = extNodeAttrs[extNodeAttrKey]; - if (extNodeAttr.nodeName && extNodeAttr.nodeValue) { ext.attributes[extNodeAttr.nodeName] = extNodeAttr.nodeValue; } } } - } // Parse all children - + } + // Parse all children for (var childNodeKey in childNodes) { if (childNodes.hasOwnProperty(childNodeKey)) { var parsedChild = _parseExtension(childNodes[childNodeKey]); - if (parsedChild) { ext.children.push(parsedChild); } } } + /* Only parse value of Nodes with only eather no children or only a cdata or text to avoid useless parsing that would result to a concatenation of all children */ - - if (ext.children.length === 0 || ext.children.length === 1 && ['#cdata-section', '#text'].indexOf(ext.children[0].name) >= 0) { var txt = parserUtils.parseNodeText(extNode); - if (txt !== '') { ext.value = txt; - } // Remove the children if it's a cdata or simply text to avoid useless children - + } + // Remove the children if it's a cdata or simply text to avoid useless children ext.children = []; - } // Only return not empty objects to not pollute extentions - + } + // Only return not empty objects to not pollute extentions return isEmptyExtension(ext) ? null : ext; } @@ -1533,7 +1444,6 @@ * @param {any} creativeNodes - The creative nodes to parse. * @return {Array} - An array of Creative objects. */ - function parseCreatives(creativeNodes) { var creatives = []; creativeNodes.forEach(function (creativeElement) { @@ -1554,54 +1464,49 @@ }); var creativeExtensions; var creativeExtensionsElement = parserUtils.childByName(creativeElement, 'CreativeExtensions'); - if (creativeExtensionsElement) { creativeExtensions = parseExtensions(parserUtils.childrenByName(creativeExtensionsElement, 'CreativeExtension')); } - for (var creativeTypeElementKey in creativeElement.childNodes) { var creativeTypeElement = creativeElement.childNodes[creativeTypeElementKey]; var parsedCreative = void 0; - switch (creativeTypeElement.nodeName) { case 'Linear': parsedCreative = parseCreativeLinear(creativeTypeElement, creativeAttributes); break; - case 'NonLinearAds': parsedCreative = parseCreativeNonLinear(creativeTypeElement, creativeAttributes); break; - case 'CompanionAds': parsedCreative = parseCreativeCompanion(creativeTypeElement, creativeAttributes); break; } - if (parsedCreative) { if (universalAdIds) { parsedCreative.universalAdIds = universalAdIds; } - if (creativeExtensions) { parsedCreative.creativeExtensions = creativeExtensions; } - creatives.push(parsedCreative); } } }); return creatives; } + /** * Parses the creative adId Attribute. * @param {any} creativeElement - The creative element to retrieve the adId from. * @return {String|null} */ - function parseCreativeAdIdAttribute(creativeElement) { - return creativeElement.getAttribute('AdID') || // VAST 2 spec - creativeElement.getAttribute('adID') || // VAST 3 spec - creativeElement.getAttribute('adId') || // VAST 4 spec + return creativeElement.getAttribute('AdID') || + // VAST 2 spec + creativeElement.getAttribute('adID') || + // VAST 3 spec + creativeElement.getAttribute('adId') || + // VAST 4 spec null; } @@ -1682,21 +1587,16 @@ * @emits VASTParser#VAST-warning * @param {undefined|Boolean} [isAdInline] - Passed recursively to itself. True if the node is contained inside a inLine tag. */ - function verifyRequiredValues(node, emit, isAdInline) { if (!node || !node.nodeName) { return; } - if (node.nodeName === 'InLine') { isAdInline = true; } - verifyRequiredAttributes(node, emit); - if (hasSubElements(node)) { verifyRequiredSubElements(node, emit, isAdInline); - for (var i = 0; i < node.children.length; i++) { verifyRequiredValues(node.children[i], emit, isAdInline); } @@ -1707,24 +1607,21 @@ }, emit); } } + /** * Verify and trigger warnings if node required attributes are not set. * @param {Node} node - The node element. * @param {Function} emit - Emit function used to trigger Warning event. * @emits VASTParser#VAST-warning */ - - function verifyRequiredAttributes(node, emit) { if (!requiredValues[node.nodeName] || !requiredValues[node.nodeName].attributes) { return; } - var requiredAttributes = requiredValues[node.nodeName].attributes; var missingAttributes = requiredAttributes.filter(function (attributeName) { return !node.getAttribute(attributeName); }); - if (missingAttributes.length > 0) { emitMissingValueWarning({ name: node.nodeName, @@ -1733,6 +1630,7 @@ }, emit); } } + /** * Verify and trigger warnings if node required sub element are not set. * @param {Node} node - The node element @@ -1740,24 +1638,19 @@ * @param {Function} emit - Emit function used to trigger Warning event. * @emits VASTParser#VAST-warning */ - - function verifyRequiredSubElements(node, emit, isAdInline) { - var required = requiredValues[node.nodeName]; // Do not verify subelement if node is a child of wrapper, but verify it if node is the Wrapper itself + var required = requiredValues[node.nodeName]; + // Do not verify subelement if node is a child of wrapper, but verify it if node is the Wrapper itself // Wrapper child have no required subElement. (Only InLine does) - var isInWrapperButNotWrapperItself = !isAdInline && node.nodeName !== 'Wrapper'; - if (!required || isInWrapperButNotWrapperItself) { return; } - if (required.subElements) { var requiredSubElements = required.subElements; var missingSubElements = requiredSubElements.filter(function (subElementName) { return !parserUtils.childByName(node, subElementName); }); - if (missingSubElements.length > 0) { emitMissingValueWarning({ name: node.nodeName, @@ -1765,18 +1658,16 @@ subElements: missingSubElements }, emit); } - } // When InLine format is used some nodes (i.e , , or ) - // require at least one of the following resources: StaticResource, IFrameResource, HTMLResource - + } + // When InLine format is used some nodes (i.e , , or ) + // require at least one of the following resources: StaticResource, IFrameResource, HTMLResource if (!isAdInline || !required.oneOfinLineResources) { return; } - var resourceFound = required.oneOfinLineResources.some(function (resource) { return parserUtils.childByName(node, resource); }); - if (!resourceFound) { emitMissingValueWarning({ name: node.nodeName, @@ -1785,16 +1676,16 @@ }, emit); } } + /** * Check if a node has sub elements. * @param {Node} node - The node element. * @returns {Boolean} */ - - function hasSubElements(node) { return node.children && node.children.length !== 0; } + /** * Trigger Warning if a element is empty or has missing attributes/subelements/resources * @param {Object} missingElement - Object containing missing elements and values @@ -1806,16 +1697,13 @@ * @param {Function} emit - Emit function used to trigger Warning event. * @emits VastParser#VAST-warning */ - - function emitMissingValueWarning(_ref, emit) { var name = _ref.name, - parentName = _ref.parentName, - attributes = _ref.attributes, - subElements = _ref.subElements, - oneOfResources = _ref.oneOfResources; + parentName = _ref.parentName, + attributes = _ref.attributes, + subElements = _ref.subElements, + oneOfResources = _ref.oneOfResources; var message = "Element '".concat(name, "'"); - if (attributes) { message += " missing required attribute(s) '".concat(attributes.join(', '), "' "); } else if (subElements) { @@ -1825,14 +1713,12 @@ } else { message += " is empty"; } - emit('VAST-warning', { message: message, parentElement: parentName, specVersion: 4.1 }); } - var parserVerification = { verifyRequiredValues: verifyRequiredValues, hasSubElements: hasSubElements, @@ -1853,29 +1739,22 @@ * @emits VASTParser#VAST-warning * @return {Object|undefined} - Object containing the ad and if it is wrapper/inline */ - function parseAd(adElement, emit) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - allowMultipleAds = _ref.allowMultipleAds, - followAdditionalWrappers = _ref.followAdditionalWrappers; - + allowMultipleAds = _ref.allowMultipleAds, + followAdditionalWrappers = _ref.followAdditionalWrappers; var childNodes = adElement.childNodes; - for (var adTypeElementKey in childNodes) { var adTypeElement = childNodes[adTypeElementKey]; - if (['Wrapper', 'InLine'].indexOf(adTypeElement.nodeName) === -1) { continue; } - if (adTypeElement.nodeName === 'Wrapper' && followAdditionalWrappers === false) { continue; } - parserUtils.copyNodeAttribute('id', adElement, adTypeElement); parserUtils.copyNodeAttribute('sequence', adElement, adTypeElement); parserUtils.copyNodeAttribute('adType', adElement, adTypeElement); - if (adTypeElement.nodeName === 'Wrapper') { return { ad: parseWrapper(adTypeElement, emit), @@ -1891,6 +1770,7 @@ } } } + /** * Parses an Inline * @param {Object} adElement Element - The VAST Inline element to parse. @@ -1899,20 +1779,18 @@ * @emits VASTParser#VAST-warning * @return {Object} ad - The ad object. */ - function parseInLine(adElement, emit) { var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - allowMultipleAds = _ref2.allowMultipleAds; - + allowMultipleAds = _ref2.allowMultipleAds; // if allowMultipleAds is set to false by wrapper attribute // only the first stand-alone Ad (with no sequence values) in the // requested VAST response is allowed so we won't parse ads with sequence if (allowMultipleAds === false && adElement.getAttribute('sequence')) { return null; } - return parseAdElement(adElement, emit); } + /** * Parses an ad type (Inline or Wrapper) * @param {Object} adTypeElement - The VAST Inline or Wrapper element to parse. @@ -1920,99 +1798,79 @@ * @emits VASTParser#VAST-warning * @return {Object} ad - The ad object. */ - - function parseAdElement(adTypeElement, emit) { var adVerificationsFromExtensions = []; - if (emit) { parserVerification.verifyRequiredValues(adTypeElement, emit); } - var childNodes = adTypeElement.childNodes; var ad = createAd(parserUtils.parseAttributes(adTypeElement)); - for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - switch (node.nodeName) { case 'Error': ad.errorURLTemplates.push(parserUtils.parseNodeText(node)); break; - case 'Impression': ad.impressionURLTemplates.push({ id: node.getAttribute('id') || null, url: parserUtils.parseNodeText(node) }); break; - case 'Creatives': ad.creatives = parseCreatives(parserUtils.childrenByName(node, 'Creative')); break; - case 'Extensions': { var extNodes = parserUtils.childrenByName(node, 'Extension'); ad.extensions = parseExtensions(extNodes); + /* OMID specify adVerifications should be in extensions for VAST < 4.0 To avoid to put them on two different places in two different format we reparse it from extensions the same way than for an AdVerifications node. */ - if (!ad.adVerifications.length) { adVerificationsFromExtensions = _parseAdVerificationsFromExtensions(extNodes); } - break; } - case 'AdVerifications': ad.adVerifications = _parseAdVerifications(parserUtils.childrenByName(node, 'Verification')); break; - case 'AdSystem': ad.system = { value: parserUtils.parseNodeText(node), version: node.getAttribute('version') || null }; break; - case 'AdTitle': ad.title = parserUtils.parseNodeText(node); break; - case 'AdServingId': ad.adServingId = parserUtils.parseNodeText(node); break; - case 'Category': ad.categories.push({ authority: node.getAttribute('authority') || null, value: parserUtils.parseNodeText(node) }); break; - case 'Expires': ad.expires = parseInt(parserUtils.parseNodeText(node), 10); break; - case 'ViewableImpression': ad.viewableImpression.push(_parseViewableImpression(node)); break; - case 'Description': ad.description = parserUtils.parseNodeText(node); break; - case 'Advertiser': ad.advertiser = { id: node.getAttribute('id') || null, value: parserUtils.parseNodeText(node) }; break; - case 'Pricing': ad.pricing = { value: parserUtils.parseNodeText(node), @@ -2020,11 +1878,12 @@ currency: node.getAttribute('currency') || null }; break; - case 'Survey': - ad.survey = parserUtils.parseNodeText(node); + ad.survey = { + value: parserUtils.parseNodeText(node), + type: node.getAttribute('type') || null + }; break; - case 'BlockedAdCategories': ad.blockedAdCategories.push({ authority: node.getAttribute('authority') || null, @@ -2033,13 +1892,12 @@ break; } } - if (adVerificationsFromExtensions.length) { ad.adVerifications = ad.adVerifications.concat(adVerificationsFromExtensions); } - return ad; } + /** * Parses a Wrapper element without resolving the wrapped urls. * @param {Object} wrapperElement - The VAST Wrapper element to be parsed. @@ -2047,8 +1905,6 @@ * @emits VASTParser#VAST-warning * @return {Ad} */ - - function parseWrapper(wrapperElement, emit) { var ad = parseAdElement(wrapperElement, emit); var followAdditionalWrappersValue = wrapperElement.getAttribute('followAdditionalWrappers'); @@ -2058,17 +1914,14 @@ ad.allowMultipleAds = allowMultipleAdsValue ? parserUtils.parseBoolean(allowMultipleAdsValue) : false; ad.fallbackOnNoAd = fallbackOnNoAdValue ? parserUtils.parseBoolean(fallbackOnNoAdValue) : null; var wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURI'); - if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(wrapperURLElement); } else { wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURL'); - if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(parserUtils.childByName(wrapperURLElement, 'URL')); } } - ad.creatives.forEach(function (wrapperCreativeElement) { if (['linear', 'nonlinear'].indexOf(wrapperCreativeElement.type) !== -1) { // TrackingEvents Linear / NonLinear @@ -2076,172 +1929,139 @@ if (!ad.trackingEvents) { ad.trackingEvents = {}; } - if (!ad.trackingEvents[wrapperCreativeElement.type]) { ad.trackingEvents[wrapperCreativeElement.type] = {}; } - var _loop = function _loop(eventName) { var urls = wrapperCreativeElement.trackingEvents[eventName]; - if (!Array.isArray(ad.trackingEvents[wrapperCreativeElement.type][eventName])) { ad.trackingEvents[wrapperCreativeElement.type][eventName] = []; } - urls.forEach(function (url) { ad.trackingEvents[wrapperCreativeElement.type][eventName].push(url); }); }; - for (var eventName in wrapperCreativeElement.trackingEvents) { _loop(eventName); } - } // ClickTracking - - + } + // ClickTracking if (wrapperCreativeElement.videoClickTrackingURLTemplates) { if (!Array.isArray(ad.videoClickTrackingURLTemplates)) { ad.videoClickTrackingURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged - - wrapperCreativeElement.videoClickTrackingURLTemplates.forEach(function (item) { ad.videoClickTrackingURLTemplates.push(item); }); - } // ClickThrough - - + } + // ClickThrough if (wrapperCreativeElement.videoClickThroughURLTemplate) { ad.videoClickThroughURLTemplate = wrapperCreativeElement.videoClickThroughURLTemplate; - } // CustomClick - - + } + // CustomClick if (wrapperCreativeElement.videoCustomClickURLTemplates) { if (!Array.isArray(ad.videoCustomClickURLTemplates)) { ad.videoCustomClickURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged - - wrapperCreativeElement.videoCustomClickURLTemplates.forEach(function (item) { ad.videoCustomClickURLTemplates.push(item); }); } } }); - if (ad.nextWrapperURL) { return ad; } } + /** * Parses the AdVerifications Element. * @param {Array} verifications - The array of verifications to parse. * @return {Array} */ - - function _parseAdVerifications(verifications) { var ver = []; verifications.forEach(function (verificationNode) { var verification = createAdVerification(); var childNodes = verificationNode.childNodes; parserUtils.assignAttributes(verificationNode.attributes, verification); - for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - switch (node.nodeName) { case 'JavaScriptResource': case 'ExecutableResource': verification.resource = parserUtils.parseNodeText(node); parserUtils.assignAttributes(node.attributes, verification); break; - case 'VerificationParameters': verification.parameters = parserUtils.parseNodeText(node); break; } } - var trackingEventsElement = parserUtils.childByName(verificationNode, 'TrackingEvents'); - if (trackingEventsElement) { parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { var eventName = trackingElement.getAttribute('event'); var trackingURLTemplate = parserUtils.parseNodeText(trackingElement); - if (eventName && trackingURLTemplate) { if (!Array.isArray(verification.trackingEvents[eventName])) { verification.trackingEvents[eventName] = []; } - verification.trackingEvents[eventName].push(trackingURLTemplate); } }); } - ver.push(verification); }); return ver; } + /** * Parses the AdVerifications Element from extension for versions < 4.0 * @param {Array} extensions - The array of extensions to parse. * @return {Array} */ - function _parseAdVerificationsFromExtensions(extensions) { var adVerificationsNode = null, - adVerifications = []; // Find the first (and only) AdVerifications node from extensions + adVerifications = []; + // Find the first (and only) AdVerifications node from extensions extensions.some(function (extension) { return adVerificationsNode = parserUtils.childByName(extension, 'AdVerifications'); - }); // Parse it if we get it + }); + // Parse it if we get it if (adVerificationsNode) { adVerifications = _parseAdVerifications(parserUtils.childrenByName(adVerificationsNode, 'Verification')); } - return adVerifications; } + /** * Parses the ViewableImpression Element. * @param {Object} viewableImpressionNode - The ViewableImpression node element. * @return {Object} viewableImpression - The viewableImpression object */ - function _parseViewableImpression(viewableImpressionNode) { - var viewableImpression = {}; - viewableImpression.id = viewableImpressionNode.getAttribute('id') || null; - var viewableImpressionChildNodes = viewableImpressionNode.childNodes; - - for (var viewableImpressionElementKey in viewableImpressionChildNodes) { - var viewableImpressionElement = viewableImpressionChildNodes[viewableImpressionElementKey]; - var viewableImpressionNodeName = viewableImpressionElement.nodeName; - var viewableImpressionNodeValue = parserUtils.parseNodeText(viewableImpressionElement); - - if (viewableImpressionNodeName !== 'Viewable' && viewableImpressionNodeName !== 'NotViewable' && viewableImpressionNodeName !== 'ViewUndetermined' || !viewableImpressionNodeValue) { - continue; - } else { - var viewableImpressionNodeNameLower = viewableImpressionNodeName.toLowerCase(); - - if (!Array.isArray(viewableImpression[viewableImpressionNodeNameLower])) { - viewableImpression[viewableImpressionNodeNameLower] = []; - } - - viewableImpression[viewableImpressionNodeNameLower].push(viewableImpressionNodeValue); - } - } - - return viewableImpression; + var regroupNodesUrl = function regroupNodesUrl(urls, node) { + var url = parserUtils.parseNodeText(node); + url && urls.push(url); + return urls; + }; + return { + id: viewableImpressionNode.getAttribute('id') || null, + viewable: parserUtils.childrenByName(viewableImpressionNode, 'Viewable').reduce(regroupNodesUrl, []), + notViewable: parserUtils.childrenByName(viewableImpressionNode, 'NotViewable').reduce(regroupNodesUrl, []), + viewUndetermined: parserUtils.childrenByName(viewableImpressionNode, 'ViewUndetermined').reduce(regroupNodesUrl, []) + }; } var EventEmitter = /*#__PURE__*/function () { function EventEmitter() { _classCallCheck(this, EventEmitter); - this._handlers = []; } + /** * Adds the event name and handler function to the end of the handlers array. * No checks are made to see if the handler has already been added. @@ -2251,26 +2071,22 @@ * @param {Function} handler * @returns {EventEmitter} */ - - _createClass(EventEmitter, [{ key: "on", value: function on(event, handler) { if (typeof handler !== 'function') { throw new TypeError("The handler argument must be of type Function. Received type ".concat(_typeof(handler))); } - if (!event) { throw new TypeError("The event argument must be of type String. Received type ".concat(_typeof(event))); } - this._handlers.push({ event: event, handler: handler }); - return this; } + /** * Adds a one-time handler function for the named event. * The next time event is triggered, this handler is removed and then invoked. @@ -2278,19 +2094,18 @@ * @param {Function} handler * @returns {EventEmitter} */ - }, { key: "once", value: function once(event, handler) { return this.on(event, onceWrap(this, event, handler)); } + /** * Removes all instances for the specified handler from the handler array for the named event. * @param {String} event * @param {Function} handler * @returns {EventEmitter} */ - }, { key: "off", value: function off(event, handler) { @@ -2299,6 +2114,7 @@ }); return this; } + /** * Synchronously calls each of the handlers registered for the named event, * in the order they were registered, passing the supplied arguments to each. @@ -2306,36 +2122,31 @@ * @param {...any} args list of arguments that will be used by the event handler * @returns {Boolean} true if the event had handlers, false otherwise. */ - }, { key: "emit", value: function emit(event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } - var called = false; - this._handlers.forEach(function (item) { if (item.event === '*') { called = true; item.handler.apply(item, [event].concat(args)); } - if (item.event === event) { called = true; item.handler.apply(item, args); } }); - return called; } + /** * Removes all listeners, or those of the specified named event. * @param {String} event * @returns {EventEmitter} */ - }, { key: "removeAllListeners", value: function removeAllListeners(event) { @@ -2343,18 +2154,17 @@ this._handlers = []; return this; } - this._handlers = this._handlers.filter(function (item) { return item.event !== event; }); return this; } + /** * Returns the number of listeners listening to the named event. * @param {String} event * @returns {Number} */ - }, { key: "listenerCount", value: function listenerCount(event) { @@ -2362,12 +2172,12 @@ return item.event === event; }).length; } + /** * Returns a copy of the array of listeners for the named event including those created by .once(). * @param {String} event * @returns {Function[]} */ - }, { key: "listeners", value: function listeners(event) { @@ -2375,15 +2185,14 @@ if (item.event === event) { listeners.push(item.handler); } - return listeners; }, []); } + /** * Returns an array listing the events for which the emitter has registered handlers. * @returns {String[]} */ - }, { key: "eventNames", value: function eventNames() { @@ -2392,16 +2201,13 @@ }); } }]); - return EventEmitter; }(); - function onceWrap(target, event, handler) { var state = { fired: false, wrapFn: undefined }; - function onceWrapper() { if (!state.fired) { target.off(event, state.wrapFn); @@ -2409,7 +2215,6 @@ handler.bind(target).apply(void 0, arguments); } } - state.wrapFn = onceWrapper; return onceWrapper; } @@ -2420,7 +2225,6 @@ function get$2(url, options, cb) { cb(new Error('Please bundle the library for node to use the node urlHandler')); } - var nodeURLHandler = { get: get$2 }; @@ -2430,22 +2234,18 @@ function xhr() { try { var request = new window.XMLHttpRequest(); - if ('withCredentials' in request) { // check CORS support return request; } - return null; } catch (err) { return null; } } - function supported() { return !!xhr(); } - function handleLoad(request, cb) { if (request.status === 200) { cb(null, request.responseXML, { @@ -2456,50 +2256,40 @@ handleFail(request, cb, false); } } - function handleFail(request, cb, isTimeout) { var statusCode = !isTimeout ? request.status : 408; // Request timeout - var msg = isTimeout ? "XHRURLHandler: Request timed out after ".concat(request.timeout, " ms (").concat(statusCode, ")") : "XHRURLHandler: ".concat(request.statusText, " (").concat(statusCode, ")"); cb(new Error(msg), null, { statusCode: statusCode }); } - function get$1(url, options, cb) { if (window.location.protocol === 'https:' && url.indexOf('http://') === 0) { return cb(new Error('XHRURLHandler: Cannot go from HTTPS to HTTP.')); } - try { var request = xhr(); request.open('GET', url); request.timeout = options.timeout || DEFAULT_TIMEOUT; request.withCredentials = options.withCredentials || false; request.overrideMimeType && request.overrideMimeType('text/xml'); - request.onload = function () { return handleLoad(request, cb); }; - request.onerror = function () { return handleFail(request, cb, false); }; - request.onabort = function () { return handleFail(request, cb, false); }; - request.ontimeout = function () { return handleFail(request, cb, true); }; - request.send(); } catch (error) { cb(new Error('XHRURLHandler: Unexpected error')); } } - var XHRURLHandler = { get: get$1, supported: supported @@ -2511,27 +2301,23 @@ if (typeof options === 'function') { cb = options; } - options = {}; } - if (typeof window === 'undefined' || window === null) { return nodeURLHandler.get(url, options, cb); } else if (XHRURLHandler.supported()) { return XHRURLHandler.get(url, options, cb); } - return cb(new Error('Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler')); } - var urlHandler = { get: get }; function createVASTResponse(_ref) { var ads = _ref.ads, - errorURLTemplates = _ref.errorURLTemplates, - version = _ref.version; + errorURLTemplates = _ref.errorURLTemplates, + version = _ref.version; return { ads: ads || [], errorURLTemplates: errorURLTemplates || [], @@ -2542,20 +2328,21 @@ /* We decided to put the estimated bitrate separated from classes to persist it between different instances of vast client/parser */ + var estimatedBitrateCount = 0; var estimatedBitrate = 0; + /** * Calculate average estimated bitrate from the previous values and new entries * @param {Number} byteLength - The length of the response in bytes. * @param {Number} duration - The duration of the request in ms. */ - var updateEstimatedBitrate = function updateEstimatedBitrate(byteLength, duration) { if (!byteLength || !duration || byteLength <= 0 || duration <= 0) { return; - } // We want the bitrate in kb/s, byteLength are in bytes and duration in ms, just need to convert the byteLength because kb/s = b/ms - + } + // We want the bitrate in kb/s, byteLength are in bytes and duration in ms, just need to convert the byteLength because kb/s = b/ms var bitrate = byteLength * 8 / duration; estimatedBitrate = (estimatedBitrate * estimatedBitrateCount + bitrate) / ++estimatedBitrateCount; }; @@ -2565,30 +2352,25 @@ ERRORCODE: 900, extensions: [] }; + /** * This class provides methods to fetch and parse a VAST document. * @export * @class VASTParser * @extends EventEmitter */ - var VASTParser = /*#__PURE__*/function (_EventEmitter) { _inherits(VASTParser, _EventEmitter); - var _super = _createSuper(VASTParser); - /** * Creates an instance of VASTParser. * @constructor */ function VASTParser() { var _this; - _classCallCheck(this, VASTParser); - _this = _super.call(this); _this.remainingAds = []; - _this.parentURLs = []; _this.errorURLTemplates = []; _this.rootErrorURLTemplates = []; _this.maxWrapperDepth = null; @@ -2597,13 +2379,12 @@ _this.parsingOptions = {}; return _this; } + /** * Adds a filter function to the array of filters which are called before fetching a VAST document. * @param {function} filter - The filter function to be added at the end of the array. * @return {void} */ - - _createClass(VASTParser, [{ key: "addURLTemplateFilter", value: function addURLTemplateFilter(filter) { @@ -2611,36 +2392,37 @@ this.URLTemplateFilters.push(filter); } } + /** * Removes the last element of the url templates filters array. * @return {void} */ - }, { key: "removeURLTemplateFilter", value: function removeURLTemplateFilter() { this.URLTemplateFilters.pop(); } + /** * Returns the number of filters of the url templates filters array. * @return {Number} */ - }, { key: "countURLTemplateFilters", value: function countURLTemplateFilters() { return this.URLTemplateFilters.length; } + /** * Removes all the filter functions from the url templates filters array. * @return {void} */ - }, { key: "clearURLTemplateFilters", value: function clearURLTemplateFilters() { this.URLTemplateFilters = []; } + /** * Tracks the error provided in the errorCode parameter and emits a VAST-error event for the given error. * @param {Array} urlTemplates - An Array of url templates to use to make the tracking call. @@ -2649,37 +2431,36 @@ * @emits VASTParser#VAST-error * @return {void} */ - }, { key: "trackVastError", value: function trackVastError(urlTemplates, errorCode) { for (var _len = arguments.length, data = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { data[_key - 2] = arguments[_key]; } - this.emit('VAST-error', Object.assign.apply(Object, [{}, DEFAULT_EVENT_DATA, errorCode].concat(data))); util.track(urlTemplates, errorCode); } + /** * Returns an array of errorURLTemplates for the VAST being parsed. * @return {Array} */ - }, { key: "getErrorURLTemplates", value: function getErrorURLTemplates() { return this.rootErrorURLTemplates.concat(this.errorURLTemplates); } + /** * Returns the estimated bitrate calculated from all previous requests * @returns The average of all estimated bitrates in kb/s. */ - }, { key: "getEstimatedBitrate", value: function getEstimatedBitrate() { return estimatedBitrate; } + /** * Fetches a VAST document for the given url. * Returns a Promise which resolves,rejects according to the result of the request. @@ -2691,12 +2472,10 @@ * @emits VASTParser#VAST-resolved * @return {Promise} */ - }, { key: "fetchVAST", value: function fetchVAST(url) { var _this2 = this; - var wrapperDepth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var previousUrl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var wrapperAd = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; @@ -2705,11 +2484,7 @@ _this2.URLTemplateFilters.forEach(function (filter) { url = filter(url); }); - - _this2.parentURLs.push(url); - var timeBeforeGet = Date.now(); - _this2.emit('VAST-resolving', { url: url, previousUrl: previousUrl, @@ -2718,7 +2493,6 @@ timeout: _this2.fetchingOptions.timeout, wrapperAd: wrapperAd }); - _this2.urlHandler.get(url, _this2.fetchingOptions, function (error, xml) { var details = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var deltaTime = Math.round(Date.now() - timeBeforeGet); @@ -2729,11 +2503,8 @@ error: error, duration: deltaTime }, details); - _this2.emit('VAST-resolved', info); - updateEstimatedBitrate(details.byteLength, deltaTime); - if (error) { reject(error); } else { @@ -2742,11 +2513,11 @@ }); }); } + /** * Inits the parsing properties of the class with the custom values provided as options. * @param {Object} options - The options to initialize a parsing sequence */ - }, { key: "initParsingStatus", value: function initParsingStatus() { @@ -2757,7 +2528,6 @@ withCredentials: options.withCredentials }; this.maxWrapperDepth = options.wrapperLimit || DEFAULT_MAX_WRAPPER_DEPTH; - this.parentURLs = []; this.parsingOptions = { allowMultipleAds: options.allowMultipleAds }; @@ -2768,24 +2538,21 @@ this.vastVersion = null; updateEstimatedBitrate(options.byteLength, options.requestDuration); } + /** * Resolves the next group of ads. If all is true resolves all the remaining ads. * @param {Boolean} all - If true all the remaining ads are resolved * @return {Promise} */ - }, { key: "getRemainingAds", value: function getRemainingAds(all) { var _this3 = this; - if (this.remainingAds.length === 0) { return Promise.reject(new Error('No more ads are available for the given VAST')); } - var ads = all ? util.flatten(this.remainingAds) : this.remainingAds.shift(); this.errorURLTemplates = []; - this.parentURLs = []; return this.resolveAds(ads, { wrapperDepth: 0, url: this.rootURL @@ -2793,6 +2560,7 @@ return _this3.buildVASTResponse(resolvedAds); }); } + /** * Fetches and parses a VAST for the given url. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -2803,12 +2571,10 @@ * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "getAndParseVAST", value: function getAndParseVAST(url) { var _this4 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.initParsingStatus(options); this.URLTemplateFilters.forEach(function (filter) { @@ -2824,6 +2590,7 @@ }); }); } + /** * Parses the given xml Object into a VASTResponse. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -2834,12 +2601,10 @@ * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "parseVAST", value: function parseVAST(vastXml) { var _this5 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.initParsingStatus(options); options.isRootVAST = true; @@ -2847,12 +2612,12 @@ return _this5.buildVASTResponse(ads); }); } + /** * Builds a VASTResponse which can be returned. * @param {Array} ads - An Array of unwrapped ads * @return {Object} */ - }, { key: "buildVASTResponse", value: function buildVASTResponse(ads) { @@ -2864,6 +2629,7 @@ this.completeWrapperResolving(response); return response; } + /** * Parses the given xml Object into an array of ads * Returns the array or throws an `Error` if an invalid VAST XML is provided @@ -2874,19 +2640,17 @@ * @return {Array} * @throws {Error} `vastXml` must be a valid VAST XMLDocument */ - }, { key: "parseVastXml", value: function parseVastXml(vastXml, _ref) { var _ref$isRootVAST = _ref.isRootVAST, - isRootVAST = _ref$isRootVAST === void 0 ? false : _ref$isRootVAST, - _ref$url = _ref.url, - url = _ref$url === void 0 ? null : _ref$url, - _ref$wrapperDepth = _ref.wrapperDepth, - wrapperDepth = _ref$wrapperDepth === void 0 ? 0 : _ref$wrapperDepth, - allowMultipleAds = _ref.allowMultipleAds, - followAdditionalWrappers = _ref.followAdditionalWrappers; - + isRootVAST = _ref$isRootVAST === void 0 ? false : _ref$isRootVAST, + _ref$url = _ref.url, + url = _ref$url === void 0 ? null : _ref$url, + _ref$wrapperDepth = _ref.wrapperDepth, + wrapperDepth = _ref$wrapperDepth === void 0 ? 0 : _ref$wrapperDepth, + allowMultipleAds = _ref.allowMultipleAds, + followAdditionalWrappers = _ref.followAdditionalWrappers; // check if is a valid VAST document if (!vastXml || !vastXml.documentElement || vastXml.documentElement.nodeName !== 'VAST') { this.emit('VAST-ad-parsed', { @@ -2896,26 +2660,24 @@ }); throw new Error('Invalid VAST XMLDocument'); } - var ads = []; var childNodes = vastXml.documentElement.childNodes; + /* Only parse the version of the Root VAST for now because we don't know yet how to * handle some cases like multiple wrappers in the same vast */ - var vastVersion = vastXml.documentElement.getAttribute('version'); - if (isRootVAST) { if (vastVersion) this.vastVersion = vastVersion; - } // Fill the VASTResponse object with ads and errorURLTemplates - + } + // Fill the VASTResponse object with ads and errorURLTemplates for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; - if (node.nodeName === 'Error') { - var errorURLTemplate = parserUtils.parseNodeText(node); // Distinguish root VAST url templates from ad specific ones + var errorURLTemplate = parserUtils.parseNodeText(node); + // Distinguish root VAST url templates from ad specific ones isRootVAST ? this.rootErrorURLTemplates.push(errorURLTemplate) : this.errorURLTemplates.push(errorURLTemplate); } else if (node.nodeName === 'Ad') { // allowMultipleAds was introduced in VAST 3 @@ -2927,12 +2689,10 @@ // (with no sequence values) in the requested VAST response is allowed break; } - var result = parseAd(node, this.emit.bind(this), { allowMultipleAds: allowMultipleAds, followAdditionalWrappers: followAdditionalWrappers }); - if (result.ad) { ads.push(result.ad); this.emit('VAST-ad-parsed', { @@ -2950,9 +2710,9 @@ } } } - return ads; } + /** * Parses the given xml Object into an array of unwrapped ads. * Returns a Promise which resolves with the array or rejects with an error according to the result of the parsing. @@ -2963,33 +2723,30 @@ * @emits VASTParser#VAST-warning * @return {Promise} */ - }, { key: "parse", value: function parse(vastXml) { var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref2$url = _ref2.url, - url = _ref2$url === void 0 ? null : _ref2$url, - _ref2$resolveAll = _ref2.resolveAll, - resolveAll = _ref2$resolveAll === void 0 ? true : _ref2$resolveAll, - _ref2$wrapperSequence = _ref2.wrapperSequence, - wrapperSequence = _ref2$wrapperSequence === void 0 ? null : _ref2$wrapperSequence, - _ref2$previousUrl = _ref2.previousUrl, - previousUrl = _ref2$previousUrl === void 0 ? null : _ref2$previousUrl, - _ref2$wrapperDepth = _ref2.wrapperDepth, - wrapperDepth = _ref2$wrapperDepth === void 0 ? 0 : _ref2$wrapperDepth, - _ref2$isRootVAST = _ref2.isRootVAST, - isRootVAST = _ref2$isRootVAST === void 0 ? false : _ref2$isRootVAST, - followAdditionalWrappers = _ref2.followAdditionalWrappers, - allowMultipleAds = _ref2.allowMultipleAds; - - var ads = []; // allowMultipleAds was introduced in VAST 3 as wrapper attribute + _ref2$url = _ref2.url, + url = _ref2$url === void 0 ? null : _ref2$url, + _ref2$resolveAll = _ref2.resolveAll, + resolveAll = _ref2$resolveAll === void 0 ? true : _ref2$resolveAll, + _ref2$wrapperSequence = _ref2.wrapperSequence, + wrapperSequence = _ref2$wrapperSequence === void 0 ? null : _ref2$wrapperSequence, + _ref2$previousUrl = _ref2.previousUrl, + previousUrl = _ref2$previousUrl === void 0 ? null : _ref2$previousUrl, + _ref2$wrapperDepth = _ref2.wrapperDepth, + wrapperDepth = _ref2$wrapperDepth === void 0 ? 0 : _ref2$wrapperDepth, + _ref2$isRootVAST = _ref2.isRootVAST, + isRootVAST = _ref2$isRootVAST === void 0 ? false : _ref2$isRootVAST, + followAdditionalWrappers = _ref2.followAdditionalWrappers, + allowMultipleAds = _ref2.allowMultipleAds; + var ads = []; + // allowMultipleAds was introduced in VAST 3 as wrapper attribute // for retrocompatibility set it to true for vast pre-version 3 - if (this.vastVersion && parseFloat(this.vastVersion) < 3 && isRootVAST) { allowMultipleAds = true; } - try { ads = this.parseVastXml(vastXml, { isRootVAST: isRootVAST, @@ -3001,6 +2758,7 @@ } catch (e) { return Promise.reject(e); } + /* Keep wrapper sequence value to not break AdPod when wrapper contain only one Ad. e.g,for a AdPod containing : - Inline with sequence=1 @@ -3011,25 +2769,23 @@ - Inline sequence 2, - Inline sequence 3 */ - - if (ads.length === 1 && wrapperSequence !== undefined && wrapperSequence !== null) { ads[0].sequence = wrapperSequence; - } // Split the VAST in case we don't want to resolve everything at the first time - + } + // Split the VAST in case we don't want to resolve everything at the first time if (resolveAll === false) { - this.remainingAds = parserUtils.splitVAST(ads); // Remove the first element from the remaining ads array, since we're going to resolve that element - + this.remainingAds = parserUtils.splitVAST(ads); + // Remove the first element from the remaining ads array, since we're going to resolve that element ads = this.remainingAds.shift(); } - return this.resolveAds(ads, { wrapperDepth: wrapperDepth, previousUrl: previousUrl, url: url }); } + /** * Resolves an Array of ads, recursively calling itself with the remaining ads if a no ad * response is returned for the given array. @@ -3037,42 +2793,35 @@ * @param {Object} options - An options Object containing resolving parameters * @return {Promise} */ - }, { key: "resolveAds", value: function resolveAds() { var _this6 = this; - var ads = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var _ref3 = arguments.length > 1 ? arguments[1] : undefined, - wrapperDepth = _ref3.wrapperDepth, - previousUrl = _ref3.previousUrl, - url = _ref3.url; - + wrapperDepth = _ref3.wrapperDepth, + previousUrl = _ref3.previousUrl, + url = _ref3.url; var resolveWrappersPromises = []; previousUrl = url; ads.forEach(function (ad) { var resolveWrappersPromise = _this6.resolveWrappers(ad, wrapperDepth, previousUrl); - resolveWrappersPromises.push(resolveWrappersPromise); }); return Promise.all(resolveWrappersPromises).then(function (unwrappedAds) { var resolvedAds = util.flatten(unwrappedAds); - if (!resolvedAds && _this6.remainingAds.length > 0) { var remainingAdsToResolve = _this6.remainingAds.shift(); - return _this6.resolveAds(remainingAdsToResolve, { wrapperDepth: wrapperDepth, previousUrl: previousUrl, url: url }); } - return resolvedAds; }); } + /** * Resolves the wrappers for the given ad in a recursive way. * Returns a Promise which resolves with the unwrapped ad or rejects with an error. @@ -3081,44 +2830,38 @@ * @param {String} previousUrl - The previous vast url. * @return {Promise} */ - }, { key: "resolveWrappers", value: function resolveWrappers(ad, wrapperDepth, previousUrl) { var _this7 = this; - return new Promise(function (resolve) { var _this7$parsingOptions; - // Going one level deeper in the wrapper chain - wrapperDepth++; // We already have a resolved VAST ad, no need to resolve wrapper - + wrapperDepth++; + // We already have a resolved VAST ad, no need to resolve wrapper if (!ad.nextWrapperURL) { delete ad.nextWrapperURL; return resolve(ad); } - - if (wrapperDepth >= _this7.maxWrapperDepth || _this7.parentURLs.indexOf(ad.nextWrapperURL) !== -1) { + if (wrapperDepth >= _this7.maxWrapperDepth) { // Wrapper limit reached, as defined by the video player. // Too many Wrapper responses have been received with no InLine response. ad.errorCode = 302; delete ad.nextWrapperURL; return resolve(ad); - } // Get full URL - + } + // Get full URL ad.nextWrapperURL = parserUtils.resolveVastAdTagURI(ad.nextWrapperURL, previousUrl); - _this7.URLTemplateFilters.forEach(function (filter) { ad.nextWrapperURL = filter(ad.nextWrapperURL); - }); // If allowMultipleAds is set inside the parameter 'option' of public method - // override the vast value by the one provided - - - var allowMultipleAds = (_this7$parsingOptions = _this7.parsingOptions.allowMultipleAds) !== null && _this7$parsingOptions !== void 0 ? _this7$parsingOptions : ad.allowMultipleAds; // sequence doesn't carry over in wrapper element + }); + // If allowMultipleAds is set inside the parameter 'option' of public method + // override the vast value by the one provided + var allowMultipleAds = (_this7$parsingOptions = _this7.parsingOptions.allowMultipleAds) !== null && _this7$parsingOptions !== void 0 ? _this7$parsingOptions : ad.allowMultipleAds; + // sequence doesn't carry over in wrapper element var wrapperSequence = ad.sequence; - _this7.fetchVAST(ad.nextWrapperURL, wrapperDepth, previousUrl, ad).then(function (xml) { return _this7.parse(xml, { url: ad.nextWrapperURL, @@ -3129,13 +2872,11 @@ allowMultipleAds: allowMultipleAds }).then(function (unwrappedAds) { delete ad.nextWrapperURL; - if (unwrappedAds.length === 0) { // No ads returned by the wrappedResponse, discard current creatives ad.creatives = []; return resolve(ad); } - unwrappedAds.forEach(function (unwrappedAd) { if (unwrappedAd) { parserUtils.mergeWrapperAdData(unwrappedAd, ad); @@ -3152,17 +2893,18 @@ }); }); } + /** * Takes care of handling errors when the wrappers are resolved. * @param {Object} vastResponse - A resolved VASTResponse. */ - }, { key: "completeWrapperResolving", value: function completeWrapperResolving(vastResponse) { // We've to wait for all elements to be parsed before handling error so we can: // - Send computed extensions data // - Ping all URIs defined across VAST files + // No Ad case - The parser never bump into an element if (vastResponse.ads.length === 0) { this.trackVastError(vastResponse.errorURLTemplates, { @@ -3174,7 +2916,6 @@ // - No Creative case - The parser has dealt with soma or/and an elements // but no creative was found var ad = vastResponse.ads[index]; - if (ad.errorCode || ad.creatives.length === 0) { this.trackVastError(ad.errorURLTemplates.concat(vastResponse.errorURLTemplates), { ERRORCODE: ad.errorCode || 303 @@ -3191,17 +2932,16 @@ } } }]); - return VASTParser; }(EventEmitter); var storage = null; + /** * This Object represents a default storage to be used in case no other storage is available. * @constant * @type {Object} */ - var DEFAULT_STORAGE = { data: {}, length: 0, @@ -3221,13 +2961,13 @@ this.length = 0; } }; + /** * This class provides an wrapper interface to the a key-value storage. * It uses localStorage, sessionStorage or a custom storage if none of the two is available. * @export * @class Storage */ - var Storage = /*#__PURE__*/function () { /** * Creates an instance of Storage. @@ -3235,35 +2975,31 @@ */ function Storage() { _classCallCheck(this, Storage); - this.storage = this.initStorage(); } + /** * Provides a singleton instance of the wrapped storage. * @return {Object} */ - - _createClass(Storage, [{ key: "initStorage", value: function initStorage() { if (storage) { return storage; } - try { storage = typeof window !== 'undefined' && window !== null ? window.localStorage || window.sessionStorage : null; } catch (storageError) { storage = null; } - if (!storage || this.isStorageDisabled(storage)) { storage = DEFAULT_STORAGE; storage.clear(); } - return storage; } + /** * Check if storage is disabled (like in certain cases with private browsing). * In Safari (Mac + iOS) when private browsing is ON, localStorage is read only @@ -3271,15 +3007,12 @@ * @param {Object} testStorage - The storage to check. * @return {Boolean} */ - }, { key: "isStorageDisabled", value: function isStorageDisabled(testStorage) { var testValue = '__VASTStorage__'; - try { testStorage.setItem(testValue, testValue); - if (testStorage.getItem(testValue) !== testValue) { testStorage.removeItem(testValue); return true; @@ -3287,55 +3020,53 @@ } catch (e) { return true; } - testStorage.removeItem(testValue); return false; } + /** * Returns the value for the given key. If the key does not exist, null is returned. * @param {String} key - The key to retrieve the value. * @return {any} */ - }, { key: "getItem", value: function getItem(key) { return this.storage.getItem(key); } + /** * Adds or updates the value for the given key. * @param {String} key - The key to modify the value. * @param {any} value - The value to be associated with the key. * @return {any} */ - }, { key: "setItem", value: function setItem(key, value) { return this.storage.setItem(key, value); } + /** * Removes an item for the given key. * @param {String} key - The key to remove the value. * @return {any} */ - }, { key: "removeItem", value: function removeItem(key) { return this.storage.removeItem(key); } + /** * Removes all the items from the storage. */ - }, { key: "clear", value: function clear() { return this.storage.clear(); } }]); - return Storage; }(); @@ -3345,7 +3076,6 @@ * @export * @class VASTClient */ - var VASTClient = /*#__PURE__*/function () { /** * Creates an instance of VASTClient. @@ -3356,7 +3086,6 @@ */ function VASTClient(cappingFreeLunch, cappingMinimumTimeInterval, customStorage) { _classCallCheck(this, VASTClient); - this.cappingFreeLunch = cappingFreeLunch || 0; this.cappingMinimumTimeInterval = cappingMinimumTimeInterval || 0; this.defaultOptions = { @@ -3364,21 +3093,19 @@ timeout: 0 }; this.vastParser = new VASTParser(); - this.storage = customStorage || new Storage(); // Init values if not already set + this.storage = customStorage || new Storage(); + // Init values if not already set if (this.lastSuccessfulAd === undefined) { this.lastSuccessfulAd = 0; } - if (this.totalCalls === undefined) { this.totalCalls = 0; } - if (this.totalCallsTimeout === undefined) { this.totalCallsTimeout = 0; } } - _createClass(VASTClient, [{ key: "getParser", value: function getParser() { @@ -3408,27 +3135,28 @@ set: function set(value) { this.storage.setItem('vast-client-total-calls-timeout', value); } + /** * Returns a boolean indicating if there are more ads to resolve for the current parsing. * @return {Boolean} */ - }, { key: "hasRemainingAds", value: function hasRemainingAds() { return this.vastParser.remainingAds.length > 0; } + /** * Resolves the next group of ads. If all is true resolves all the remaining ads. * @param {Boolean} all - If true all the remaining ads are resolved * @return {Promise} */ - }, { key: "getNextAds", value: function getNextAds(all) { return this.vastParser.getRemainingAds(all); } + /** * Gets a parsed VAST document for the given url, applying the skipping rules defined. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. @@ -3436,44 +3164,41 @@ * @param {Object} options - An optional Object of parameters to be applied in the process. * @return {Promise} */ - }, { key: "get", value: function get(url) { var _this = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var now = Date.now(); - options = Object.assign({}, this.defaultOptions, options); // By default the client resolves only the first Ad or AdPod + options = Object.assign({}, this.defaultOptions, options); + // By default the client resolves only the first Ad or AdPod if (!options.hasOwnProperty('resolveAll')) { options.resolveAll = false; - } // Check totalCallsTimeout (first call + 1 hour), if older than now, + } + + // Check totalCallsTimeout (first call + 1 hour), if older than now, // reset totalCalls number, by this way the client will be eligible again // for freelunch capping - - if (this.totalCallsTimeout < now) { this.totalCalls = 1; this.totalCallsTimeout = now + 60 * 60 * 1000; } else { this.totalCalls++; } - return new Promise(function (resolve, reject) { if (_this.cappingFreeLunch >= _this.totalCalls) { return reject(new Error("VAST call canceled \u2013 FreeLunch capping not reached yet ".concat(_this.totalCalls, "/").concat(_this.cappingFreeLunch))); } + var timeSinceLastCall = now - _this.lastSuccessfulAd; - var timeSinceLastCall = now - _this.lastSuccessfulAd; // Check timeSinceLastCall to be a positive number. If not, this mean the + // Check timeSinceLastCall to be a positive number. If not, this mean the // previous was made in the future. We reset lastSuccessfulAd value - if (timeSinceLastCall < 0) { _this.lastSuccessfulAd = 0; } else if (timeSinceLastCall < _this.cappingMinimumTimeInterval) { return reject(new Error("VAST call canceled \u2013 (".concat(_this.cappingMinimumTimeInterval, ")ms minimum interval reached"))); } - _this.vastParser.getAndParseVAST(url, options).then(function (response) { return resolve(response); })["catch"](function (err) { @@ -3482,7 +3207,6 @@ }); } }]); - return VASTClient; }(); @@ -3491,8 +3215,8 @@ * @constant * @type {Number} */ - var DEFAULT_SKIP_DELAY = -1; + /** * This class provides methods to track an ad execution. * @@ -3500,12 +3224,9 @@ * @class VASTTracker * @extends EventEmitter */ - var VASTTracker = /*#__PURE__*/function (_EventEmitter) { _inherits(VASTTracker, _EventEmitter); - var _super = _createSuper(VASTTracker); - /** * Creates an instance of VASTTracker. * @@ -3513,62 +3234,60 @@ * @param {Ad} ad - The ad to track. * @param {Creative} creative - The creative to track. * @param {Object} [variation=null] - An optional variation of the creative. + * @param {Boolean} [muted=false] - The initial muted state of the video. * @constructor */ function VASTTracker(client, ad, creative) { var _this; - var variation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - + var muted = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; _classCallCheck(this, VASTTracker); - _this = _super.call(this); _this.ad = ad; _this.creative = creative; _this.variation = variation; - _this.muted = false; + _this.muted = muted; _this.impressed = false; _this.skippable = false; - _this.trackingEvents = {}; // We need to keep the last percentage of the tracker in order to + _this.trackingEvents = {}; + // We need to keep the last percentage of the tracker in order to // calculate to trigger the events when the VAST duration is short - _this.lastPercentage = 0; - _this._alreadyTriggeredQuartiles = {}; // Tracker listeners should be notified with some events + _this._alreadyTriggeredQuartiles = {}; + // Tracker listeners should be notified with some events // no matter if there is a tracking URL or not + _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; - _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; // Duplicate the creative's trackingEvents property so we can alter it - + // Duplicate the creative's trackingEvents property so we can alter it for (var eventName in _this.creative.trackingEvents) { var events = _this.creative.trackingEvents[eventName]; _this.trackingEvents[eventName] = events.slice(0); - } // Nonlinear and companion creatives provide some tracking information at a variation level + } + + // Nonlinear and companion creatives provide some tracking information at a variation level // While linear creatives provided that at a creative level. That's why we need to // differentiate how we retrieve some tracking information. - - if (isCreativeLinear(_this.creative)) { _this._initLinearTracking(); } else { _this._initVariationTracking(); - } // If the tracker is associated with a client we add a listener to the start event - // to update the lastSuccessfulAd property. - + } + // If the tracker is associated with a client we add a listener to the start event + // to update the lastSuccessfulAd property. if (client) { _this.on('start', function () { client.lastSuccessfulAd = Date.now(); }); } - return _this; } + /** * Init the custom tracking options for linear creatives. * * @return {void} */ - - _createClass(VASTTracker, [{ key: "_initLinearTracking", value: function _initLinearTracking() { @@ -3578,35 +3297,36 @@ this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate; this.clickTrackingURLTemplates = this.creative.videoClickTrackingURLTemplates; } + /** * Init the custom tracking options for nonlinear and companion creatives. * These options are provided in the variation Object. * * @return {void} */ - }, { key: "_initVariationTracking", value: function _initVariationTracking() { this.linear = false; - this.skipDelay = DEFAULT_SKIP_DELAY; // If no variation has been provided there's nothing else to set + this.skipDelay = DEFAULT_SKIP_DELAY; + // If no variation has been provided there's nothing else to set if (!this.variation) { return; - } // Duplicate the variation's trackingEvents property so we can alter it - + } + // Duplicate the variation's trackingEvents property so we can alter it for (var eventName in this.variation.trackingEvents) { - var events = this.variation.trackingEvents[eventName]; // If for the given eventName we already had some trackingEvents provided by the creative - // we want to keep both the creative trackingEvents and the variation ones + var events = this.variation.trackingEvents[eventName]; + // If for the given eventName we already had some trackingEvents provided by the creative + // we want to keep both the creative trackingEvents and the variation ones if (this.trackingEvents[eventName]) { this.trackingEvents[eventName] = this.trackingEvents[eventName].concat(events.slice(0)); } else { this.trackingEvents[eventName] = events.slice(0); } } - if (isNonLinearAd(this.variation)) { this.clickThroughURLTemplate = this.variation.nonlinearClickThroughURLTemplate; this.clickTrackingURLTemplates = this.variation.nonlinearClickTrackingURLTemplates; @@ -3616,12 +3336,12 @@ this.clickTrackingURLTemplates = this.variation.companionClickTrackingURLTemplates; } } + /** * Sets the duration of the ad and updates the quartiles based on that. * * @param {Number} duration - The duration of the ad. */ - }, { key: "setDuration", value: function setDuration(duration) { @@ -3629,15 +3349,15 @@ if (!util.isValidTimeValue(duration)) { return; } - - this.assetDuration = duration; // beware of key names, theses are also used as event names - + this.assetDuration = duration; + // beware of key names, theses are also used as event names this.quartiles = { firstQuartile: Math.round(25 * this.assetDuration) / 100, midpoint: Math.round(50 * this.assetDuration) / 100, thirdQuartile: Math.round(75 * this.assetDuration) / 100 }; } + /** * Sets the duration of the ad and updates the quartiles based on that. * This is required for tracking time related events. @@ -3653,21 +3373,16 @@ * @emits VASTTracker#midpoint * @emits VASTTracker#thirdQuartile */ - }, { key: "setProgress", value: function setProgress(progress) { var _this2 = this; - var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - // check if progress is a valid time input if (!util.isValidTimeValue(progress) || _typeof(macros) !== 'object') { return; } - var skipDelay = this.skipDelay || DEFAULT_SKIP_DELAY; - if (skipDelay !== -1 && !this.skippable) { if (skipDelay > progress) { this.emit('skip-countdown', skipDelay - progress); @@ -3676,46 +3391,38 @@ this.emit('skip-countdown', 0); } } - if (this.assetDuration > 0) { var percent = Math.round(progress / this.assetDuration * 100); var events = []; - if (progress > 0) { events.push('start'); - for (var i = this.lastPercentage; i < percent; i++) { events.push("progress-".concat(i + 1, "%")); } - events.push("progress-".concat(Math.round(progress))); - for (var quartile in this.quartiles) { if (this.isQuartileReached(quartile, this.quartiles[quartile], progress)) { events.push(quartile); this._alreadyTriggeredQuartiles[quartile] = true; } } - this.lastPercentage = percent; } - events.forEach(function (eventName) { _this2.track(eventName, { macros: macros, once: true }); }); - if (progress < this.progress) { this.track('rewind', { macros: macros }); } } - this.progress = progress; } + /** * Checks if a quartile has been reached without have being triggered already. * @@ -3725,18 +3432,17 @@ * * @return {Boolean} */ - }, { key: "isQuartileReached", value: function isQuartileReached(quartile, time, progress) { - var quartileReached = false; // if quartile time already reached and never triggered - + var quartileReached = false; + // if quartile time already reached and never triggered if (time <= progress && !this._alreadyTriggeredQuartiles[quartile]) { quartileReached = true; } - return quartileReached; } + /** * Updates the mute state and calls the mute/unmute tracking URLs. * @@ -3745,24 +3451,21 @@ * @emits VASTTracker#mute * @emits VASTTracker#unmute */ - }, { key: "setMuted", value: function setMuted(muted) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof muted !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.muted !== muted) { this.track(muted ? 'mute' : 'unmute', { macros: macros }); } - this.muted = muted; } + /** * Update the pause state and call the resume/pause tracking URLs. * @@ -3771,24 +3474,21 @@ * @emits VASTTracker#pause * @emits VASTTracker#resume */ - }, { key: "setPaused", value: function setPaused(paused) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof paused !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.paused !== paused) { this.track(paused ? 'pause' : 'resume', { macros: macros }); } - this.paused = paused; } + /** * Updates the fullscreen state and calls the fullscreen tracking URLs. * @@ -3797,24 +3497,21 @@ * @emits VASTTracker#fullscreen * @emits VASTTracker#exitFullscreen */ - }, { key: "setFullscreen", value: function setFullscreen(fullscreen) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof fullscreen !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.fullscreen !== fullscreen) { this.track(fullscreen ? 'fullscreen' : 'exitFullscreen', { macros: macros }); } - this.fullscreen = fullscreen; } + /** * Updates the expand state and calls the expand/collapse tracking URLs. * @@ -3825,16 +3522,13 @@ * @emits VASTTracker#collapse * @emits VASTTracker#playerCollapse */ - }, { key: "setExpand", value: function setExpand(expanded) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof expanded !== 'boolean' || _typeof(macros) !== 'object') { return; } - if (this.expanded !== expanded) { this.track(expanded ? 'expand' : 'collapse', { macros: macros @@ -3843,9 +3537,9 @@ macros: macros }); } - this.expanded = expanded; } + /** * Must be called if you want to overwrite the Skipoffset value. * This will init the skip countdown duration. Then, every time setProgress() is called, @@ -3854,31 +3548,27 @@ * * @param {Number} duration - The time in seconds until the skip button is displayed. */ - }, { key: "setSkipDelay", value: function setSkipDelay(duration) { if (!util.isValidTimeValue(duration)) { return; } - this.skipDelay = duration; } + /** * Tracks an impression (can be called only once). * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#creativeView */ - }, { key: "trackImpression", value: function trackImpression() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - if (!this.impressed) { this.impressed = true; this.trackURLs(this.ad.impressionURLTemplates, macros); @@ -3887,26 +3577,76 @@ }); } } + + /** + * Tracks Viewable impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackViewableImpression", + value: function trackViewableImpression() { + var _this3 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this3.trackURLs(impression.viewable, macros); + }); + } + + /** + * Tracks NotViewable impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackNotViewableImpression", + value: function trackNotViewableImpression() { + var _this4 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this4.trackURLs(impression.notViewable, macros); + }); + } + + /** + * Tracks ViewUndetermined impression + * @param {Object} [macros = {}] An optional Object containing macros and their values to be used and replaced in the tracking calls. + */ + }, { + key: "trackUndeterminedImpression", + value: function trackUndeterminedImpression() { + var _this5 = this; + var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (_typeof(macros) !== 'object') { + return; + } + this.ad.viewableImpression.forEach(function (impression) { + _this5.trackURLs(impression.viewUndetermined, macros); + }); + } + /** * Send a request to the URI provided by the VAST element. * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code. */ - }, { key: "error", value: function error() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var isCustomCode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (_typeof(macros) !== 'object' || typeof isCustomCode !== 'boolean') { return; } - this.trackURLs(this.ad.errorURLTemplates, macros, { isCustomCode: isCustomCode }); } + /** * Send a request to the URI provided by the VAST element. * If an [ERRORCODE] macro is included, it will be substitute with errorCode. @@ -3914,22 +3654,20 @@ * @param {String} errorCode - Replaces [ERRORCODE] macro. [ERRORCODE] values are listed in the VAST specification. * @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code. */ - }, { key: "errorWithCode", value: function errorWithCode(errorCode) { var isCustomCode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (typeof errorCode !== 'string' || typeof isCustomCode !== 'boolean') { return; } - this.error({ ERRORCODE: errorCode - }, isCustomCode); //eslint-disable-next-line - + }, isCustomCode); + //eslint-disable-next-line console.log('The method errorWithCode is deprecated, please use vast tracker error method instead'); } + /** * Must be called when the user watched the linear creative until its end. * Calls the complete tracking URLs. @@ -3937,20 +3675,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#complete */ - }, { key: "complete", value: function complete() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('complete', { macros: macros }); } + /** * Must be called if the ad was not and will not be played * This is a terminal event; no other tracking events should be sent when this is used. @@ -3959,21 +3695,19 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#notUsed */ - }, { key: "notUsed", value: function notUsed() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('notUsed', { macros: macros }); this.trackingEvents = []; } + /** * An optional metric that can capture all other user interactions * under one metric such as hover-overs, or custom clicks. It should NOT replace @@ -3983,20 +3717,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#otherAdInteraction */ - }, { key: "otherAdInteraction", value: function otherAdInteraction() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('otherAdInteraction', { macros: macros }); } + /** * Must be called if the user clicked or otherwise activated a control used to * pause streaming content,* which either expands the ad within the player’s @@ -4007,20 +3739,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#acceptInvitation */ - }, { key: "acceptInvitation", value: function acceptInvitation() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('acceptInvitation', { macros: macros }); } + /** * Must be called if user activated a control to expand the creative. * Calls the adExpand tracking URLs. @@ -4028,20 +3758,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#adExpand */ - }, { key: "adExpand", value: function adExpand() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('adExpand', { macros: macros }); } + /** * Must be called when the user activated a control to reduce the creative to its original dimensions. * Calls the adCollapse tracking URLs. @@ -4049,20 +3777,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#adCollapse */ - }, { key: "adCollapse", value: function adCollapse() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('adCollapse', { macros: macros }); } + /** * Must be called if the user clicked or otherwise activated a control used to minimize the ad. * Calls the minimize tracking URLs. @@ -4070,20 +3796,18 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#minimize */ - }, { key: "minimize", value: function minimize() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('minimize', { macros: macros }); } + /** * Must be called if the player did not or was not able to execute the provided * verification code.The [REASON] macro must be filled with reason code @@ -4093,34 +3817,26 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#verificationNotExecuted */ - }, { key: "verificationNotExecuted", value: function verificationNotExecuted(vendor) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof vendor !== 'string' || _typeof(macros) !== 'object') { return; } - if (!this.ad || !this.ad.adVerifications || !this.ad.adVerifications.length) { throw new Error('No adVerifications provided'); } - if (!vendor) { throw new Error('No vendor provided, unable to find associated verificationNotExecuted'); } - var vendorVerification = this.ad.adVerifications.find(function (verifications) { return verifications.vendor === vendor; }); - if (!vendorVerification) { throw new Error("No associated verification element found for vendor: ".concat(vendor)); } - var vendorTracking = vendorVerification.trackingEvents; - if (vendorTracking && vendorTracking.verificationNotExecuted) { var verifsNotExecuted = vendorTracking.verificationNotExecuted; this.trackURLs(verifsNotExecuted, macros); @@ -4129,6 +3845,7 @@ }); } } + /** * The time that the initial ad is displayed. This time is based on * the time between the impression and either the completed length of display based @@ -4141,21 +3858,19 @@ * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#overlayViewDuration */ - }, { key: "overlayViewDuration", value: function overlayViewDuration(formattedDuration) { var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (typeof formattedDuration !== 'string' || _typeof(macros) !== 'object') { return; } - macros['ADPLAYHEAD'] = formattedDuration; this.track('overlayViewDuration', { macros: macros }); } + /** * Must be called when the player or the window is closed during the ad. * Calls the `closeLinear` (in VAST 3.0 and 4.1) and `close` tracking URLs. @@ -4164,40 +3879,36 @@ * @emits VASTTracker#closeLinear * @emits VASTTracker#close */ - }, { key: "close", value: function close() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track(this.linear ? 'closeLinear' : 'close', { macros: macros }); } + /** * Must be called when the skip button is clicked. Calls the skip tracking URLs. * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * * @emits VASTTracker#skip */ - }, { key: "skip", value: function skip() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('skip', { macros: macros }); } + /** * Must be called then loaded and buffered the creative’s media and assets either fully * or to the extent that it is ready to play the media @@ -4206,89 +3917,79 @@ * * @emits VASTTracker#loaded */ - }, { key: "load", value: function load() { var macros = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - if (_typeof(macros) !== 'object') { return; } - this.track('loaded', { macros: macros }); } + /** * Must be called when the user clicks on the creative. * It calls the tracking URLs and emits a 'clickthrough' event with the resolved * clickthrough URL when done. * - * @param {String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback + * @param {?String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback * @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls. * @emits VASTTracker#clickthrough */ - }, { key: "click", value: function click() { var fallbackClickThroughURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (fallbackClickThroughURL !== null && typeof fallbackClickThroughURL !== 'string' || _typeof(macros) !== 'object') { return; } - if (this.clickTrackingURLTemplates && this.clickTrackingURLTemplates.length) { this.trackURLs(this.clickTrackingURLTemplates, macros); - } // Use the provided fallbackClickThroughURL as a fallback - - - var clickThroughURLTemplate = this.clickThroughURLTemplate || fallbackClickThroughURL; // clone second usage of macros, which get mutated inside resolveURLTemplates + } + // Use the provided fallbackClickThroughURL as a fallback + var clickThroughURLTemplate = this.clickThroughURLTemplate || fallbackClickThroughURL; + // clone second usage of macros, which get mutated inside resolveURLTemplates var clonedMacros = _objectSpread2({}, macros); - if (clickThroughURLTemplate) { if (this.progress) { clonedMacros['ADPLAYHEAD'] = this.progressFormatted(); } - var clickThroughURL = util.resolveURLTemplates([clickThroughURLTemplate], clonedMacros)[0]; this.emit('clickthrough', clickThroughURL); } } + /** * Calls the tracking URLs for the given eventName and emits the event. * * @param {String} eventName - The name of the event. - * @param {Object} [macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls. - * @param {Boolean} [once=false] - Boolean to define if the event has to be tracked only once. + * @param {Object} options + * @param {Object} [options.macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls. + * @param {Boolean} [options.once=false] - Boolean to define if the event has to be tracked only once. * */ - }, { key: "track", value: function track(eventName) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$macros = _ref.macros, - macros = _ref$macros === void 0 ? {} : _ref$macros, - _ref$once = _ref.once, - once = _ref$once === void 0 ? false : _ref$once; - + _ref$macros = _ref.macros, + macros = _ref$macros === void 0 ? {} : _ref$macros, + _ref$once = _ref.once, + once = _ref$once === void 0 ? false : _ref$once; if (_typeof(macros) !== 'object') { return; - } // closeLinear event was introduced in VAST 3.0 + } + // closeLinear event was introduced in VAST 3.0 // Fallback to vast 2.0 close event if necessary - - if (eventName === 'closeLinear' && !this.trackingEvents[eventName] && this.trackingEvents['close']) { eventName = 'close'; } - var trackingURLTemplates = this.trackingEvents[eventName]; var isAlwaysEmitEvent = this.emitAlwaysEvents.indexOf(eventName) > -1; - if (trackingURLTemplates) { this.emit(eventName, { trackingURLTemplates: trackingURLTemplates @@ -4297,15 +3998,14 @@ } else if (isAlwaysEmitEvent) { this.emit(eventName, null); } - if (once) { delete this.trackingEvents[eventName]; - if (isAlwaysEmitEvent) { this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(eventName), 1); } } } + /** * Calls the tracking urls templates with the given macros . * @@ -4313,74 +4013,62 @@ * @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. */ - }, { key: "trackURLs", value: function trackURLs(URLTemplates) { - var _this$creative, _this$creative$univer; - + var _this$creative; var macros = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - + var validUrlTemplates = util.filterValidUrlTemplates(URLTemplates); //Avoid mutating the object received in parameters. var givenMacros = _objectSpread2({}, macros); - if (this.linear) { if (this.creative && this.creative.mediaFiles && this.creative.mediaFiles[0] && this.creative.mediaFiles[0].fileURL) { givenMacros['ASSETURI'] = this.creative.mediaFiles[0].fileURL; } - if (this.progress) { givenMacros['ADPLAYHEAD'] = this.progressFormatted(); } } - - if ((_this$creative = this.creative) !== null && _this$creative !== void 0 && (_this$creative$univer = _this$creative.universalAdIds) !== null && _this$creative$univer !== void 0 && _this$creative$univer.length) { + if ((_this$creative = this.creative) !== null && _this$creative !== void 0 && (_this$creative = _this$creative.universalAdIds) !== null && _this$creative !== void 0 && _this$creative.length) { givenMacros['UNIVERSALADID'] = this.creative.universalAdIds.map(function (universalAdId) { return universalAdId.idRegistry.concat(' ', universalAdId.value); }).join(','); } - if (this.ad) { if (this.ad.sequence) { givenMacros['PODSEQUENCE'] = this.ad.sequence; } - if (this.ad.adType) { givenMacros['ADTYPE'] = this.ad.adType; } - if (this.ad.adServingId) { givenMacros['ADSERVINGID'] = this.ad.adServingId; } - if (this.ad.categories && this.ad.categories.length) { givenMacros['ADCATEGORIES'] = this.ad.categories.map(function (category) { return category.value; }).join(','); } - if (this.ad.blockedAdCategories && this.ad.blockedAdCategories.length) { givenMacros['BLOCKEDADCATEGORIES'] = this.ad.blockedAdCategories; } } - - util.track(URLTemplates, givenMacros, options); + util.track(validUrlTemplates, givenMacros, options); } + /** * Formats time in seconds to VAST timecode (e.g. 00:00:10.000) * * @param {Number} timeInSeconds - Number in seconds * @return {String} */ - }, { key: "convertToTimecode", value: function convertToTimecode(timeInSeconds) { if (!util.isValidTimeValue(timeInSeconds)) { return ''; } - var progress = timeInSeconds * 1000; var hours = Math.floor(progress / (60 * 60 * 1000)); var minutes = Math.floor(progress / (60 * 1000) % 60); @@ -4388,25 +4076,25 @@ var milliseconds = Math.floor(progress % 1000); return "".concat(util.addLeadingZeros(hours, 2), ":").concat(util.addLeadingZeros(minutes, 2), ":").concat(util.addLeadingZeros(seconds, 2), ".").concat(util.addLeadingZeros(milliseconds, 3)); } + /** * Formats time progress in a readable string. * * @return {String} */ - }, { key: "progressFormatted", value: function progressFormatted() { return this.convertToTimecode(this.progress); } }]); - return VASTTracker; }(EventEmitter); exports.VASTClient = VASTClient; exports.VASTParser = VASTParser; exports.VASTTracker = VASTTracker; + exports.parseDuration = parseDuration; Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/dist/vast-client.min.js b/dist/vast-client.min.js index e2c1d540..6b0c570f 100644 --- a/dist/vast-client.min.js +++ b/dist/vast-client.min.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VAST={})}(this,(function(e){"use strict";function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(e){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}var m=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 g(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=A(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=E(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=b(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(y(s,t))}return i}function y(e,t){var r=(e=T(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return m.indexOf(e)>-1}));return 0===i.length?e:T(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function T(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function A(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function k(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var N={track:function(e,t,r){g(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:g,extractURLsFromTemplates:A,containsTemplateObject:k,isTemplateObjectEqual:R,encodeURIComponentRFC3986:b,replaceUrlMacros:y,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[],n=r.concat(i);return n.reduce((function(e,t){return k(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:E};function L(e){return-1!==["true","TRUE","True","1"].indexOf(e)}var w={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:L,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i3600||i>60?-1:a+n+i},splitVAST:function(e){var t=[],r=null;return e.forEach((function(i,n){if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=L(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(h(e.viewableImpression),h(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var r=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),i=r.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){N.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=r.concat(e.creatives);var n=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,a=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var o=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(o)}"linear"===e.type&&(n&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),a&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&i.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=N.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,i)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories))}};function U(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=w.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotID:e.adSlotID||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,xmlEncoded:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(w.parseAttributes(e));t.htmlResources=w.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=w.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=w.childrenByName(e,"StaticResource").reduce((function(e,t){var r=w.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=w.parseNodeText(w.childByName(e,"AltText"))||null;var r=w.childByName(e,"TrackingEvents");r&&w.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=w.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=w.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:w.parseNodeText(e)}})),t.companionClickThroughURLTemplate=w.parseNodeText(w.childByName(e,"CompanionClickThrough"))||null;var i=w.childByName(e,"AdParameters");return i&&(t.adParameters=w.parseNodeText(i),t.xmlEncoded=i.getAttribute("xmlEncoded")||null),t})),r}function C(e){return"linear"===e.type}function I(e,t){var r,i=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=w.parseDuration(w.parseNodeText(w.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=w.parseDuration(n);var o=w.childByName(e,"VideoClicks");if(o){var s=w.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:w.parseNodeText(s)}:null,w.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})),w.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})}))}var l=w.childByName(e,"AdParameters");l&&(i.adParameters=w.parseNodeText(l)),w.childrenByName(e,"TrackingEvents").forEach((function(e){w.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=w.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(w.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),w.childrenByName(e,"MediaFiles").forEach((function(e){w.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=w.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=w.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=w.parseBoolean(i));return t}(e))}));var t=w.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:w.parseBoolean(e.variableDuration),fileURL:null}}(w.parseAttributes(e));return t.fileURL=w.parseNodeText(e),t}(t));var r=w.childByName(e,"ClosedCaptionFiles");r&&w.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(w.parseAttributes(e));t.fileURL=w.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=w.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var u={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};u.id=s.getAttribute("id"),u.fileURL=w.parseNodeText(s),u.delivery=l.delivery,u.codec=s.getAttribute("codec"),u.type=l.type,u.width=parseInt(l.width,10),u.height=parseInt(l.height,10),u.fileSize=parseInt(s.getAttribute("fileSize"),10),u.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=u}}));var u=w.childByName(e,"Icons");return u&&w.childrenByName(u,"Icon").forEach((function(e){i.icons.push(function(e){var t={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};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=w.parseDuration(e.getAttribute("offset")),t.duration=w.parseDuration(e.getAttribute("duration")),w.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=w.parseNodeText(e)})),w.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=w.parseNodeText(e)})),w.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=w.parseNodeText(e)}));var r=w.childByName(e,"IconClicks");r&&(t.iconClickThroughURLTemplate=w.parseNodeText(w.childByName(r,"IconClickThrough")),w.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})));return t.iconViewTrackingURLTemplate=w.parseNodeText(w.childByName(e,"IconViewTracking")),t}(e))})),i}function x(e,t){var r=function(){var e=f(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),t=e.id,r=e.adId,i=e.sequence,n=e.apiFramework;return{id:t,adId:r,sequence:i,apiFramework:n,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return w.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;w.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=w.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),w.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=w.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=w.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=w.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),w.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=w.parseNodeText(e)})),w.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=w.parseNodeText(e)})),w.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=w.parseNodeText(e)}));var i=w.childByName(e,"AdParameters");i&&(t.adParameters=w.parseNodeText(i)),t.nonlinearClickThroughURLTemplate=w.parseNodeText(w.childByName(e,"NonLinearClickThrough")),w.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:w.parseNodeText(e)})})),r.variations.push(t)})),r}function S(e){var t=[];return e.forEach((function(e){var r=O(e);r&&t.push(r)})),t}function O(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=O(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var u=w.parseNodeText(e);""!==u&&(r.value=u),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function D(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:V(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];w.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:w.parseNodeText(e)};n.push(t)}));var a=w.childByName(e,"CreativeExtensions");for(var o in a&&(r=S(w.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=I(s,i);break;case"NonLinearAds":l=x(s,i);break;case"CompanionAds":l=U(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function V(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var P={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function B(e,t){if(P[e.nodeName]&&P[e.nodeName].attributes){var r=P[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&j({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function F(e,t,r){var i=P[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!w.childByName(e,t)}));a.length>0&&j({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return w.childByName(e,t)}))||j({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function M(e){return e.children&&0!==e.children.length}function j(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var W={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),B(t,r),M(t)){F(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(w.copyNodeAttribute("id",e,s),w.copyNodeAttribute("sequence",e,s),w.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:G(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:H(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function H(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds;return!1===i&&e.getAttribute("sequence")?null:_(e,t)}function _(e,t){var r=[];t&&W.verifyRequiredValues(e,t);var i=e.childNodes,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(w.parseAttributes(e));for(var a in i){var o=i[a];switch(o.nodeName){case"Error":n.errorURLTemplates.push(w.parseNodeText(o));break;case"Impression":n.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:w.parseNodeText(o)});break;case"Creatives":n.creatives=D(w.childrenByName(o,"Creative"));break;case"Extensions":var s=w.childrenByName(o,"Extension");n.extensions=S(s),n.adVerifications.length||(r=Y(s));break;case"AdVerifications":n.adVerifications=z(w.childrenByName(o,"Verification"));break;case"AdSystem":n.system={value:w.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":n.title=w.parseNodeText(o);break;case"AdServingId":n.adServingId=w.parseNodeText(o);break;case"Category":n.categories.push({authority:o.getAttribute("authority")||null,value:w.parseNodeText(o)});break;case"Expires":n.expires=parseInt(w.parseNodeText(o),10);break;case"ViewableImpression":n.viewableImpression.push(X(o));break;case"Description":n.description=w.parseNodeText(o);break;case"Advertiser":n.advertiser={id:o.getAttribute("id")||null,value:w.parseNodeText(o)};break;case"Pricing":n.pricing={value:w.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":n.survey=w.parseNodeText(o);break;case"BlockedAdCategories":n.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:w.parseNodeText(o)})}}return r.length&&(n.adVerifications=n.adVerifications.concat(r)),n}function G(e,t){var r=_(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||w.parseBoolean(i),r.allowMultipleAds=!!n&&w.parseBoolean(n),r.fallbackOnNoAd=a?w.parseBoolean(a):null;var o=w.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=w.parseNodeText(o):(o=w.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=w.parseNodeText(w.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function z(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in w.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=w.parseNodeText(a),w.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=w.parseNodeText(a)}}var o=w.childByName(e,"TrackingEvents");o&&w.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=w.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function Y(e){var t=null,r=[];return e.some((function(e){return t=w.childByName(e,"AdVerifications")})),t&&(r=z(w.childrenByName(t,"Verification"))),r}function X(e){var t={};t.id=e.getAttribute("id")||null;var r=e.childNodes;for(var i in r){var n=r[i],a=n.nodeName,o=w.parseNodeText(n);if(("Viewable"===a||"NotViewable"===a||"ViewUndetermined"===a)&&o){var s=a.toLowerCase();Array.isArray(t[s])||(t[s]=[]),t[s].push(o)}}return t}var K=function(){function e(){n(this,e),this._handlers=[]}return o(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(i(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(i(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)})),t.parentURLs.push(e);var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},c=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:c},u);t.emit("VAST-resolved",d),ne(u.byteLength,c),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||Z,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parentURLs=[],this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||te,this.vastVersion=null,ne(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?N.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.parentURLs=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,u=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var c=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=w.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&c.length>1)break;var m=q(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:u});m.ad?(c.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:c.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,u=void 0===l?null:l,c=t.wrapperDepth,d=void 0===c?0:c,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=w.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:u,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=N.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth||-1!==i.parentURLs.indexOf(e.nextWrapperURL))return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=w.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&w.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(K),se=null,le={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},ue=function(){function e(){n(this,e),this.storage=this.initStorage()}return o(e,[{key:"initStorage",value:function(){if(se)return se;try{se="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){se=null}return se&&!this.isStorageDisabled(se)||(se=le).clear(),se}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),ce=function(){function e(t,r,i){n(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new oe,this.storage=i||new ue,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return o(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null;for(var l in n(this,a),(o=t.call(this)).ad=r,o.creative=i,o.variation=s,o.muted=!1,o.impressed=!1,o.skippable=!1,o.trackingEvents={},o.lastPercentage=0,o._alreadyTriggeredQuartiles={},o.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],o.creative.trackingEvents){var u=o.creative.trackingEvents[l];o.trackingEvents[l]=u.slice(0)}return C(o.creative)?o._initLinearTracking():o._initVariationTracking(),e&&o.on("start",(function(){e.lastSuccessfulAd=Date.now()})),o}return o(a,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){N.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(N.isValidTimeValue(e)&&"object"===i(r)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){N.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===i(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===i(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var r=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));var n=r.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===i(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===i(t)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);var n=this.clickThroughURLTemplate||e,a=r({},t);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=N.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.macros,n=void 0===r?{}:r,a=t.once,o=void 0!==a&&a;if("object"===i(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var t,i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=r({},n);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(i=t.universalAdIds)&&void 0!==i&&i.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),N.track(e,o,a)}},{key:"convertToTimecode",value:function(e){if(!N.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(N.addLeadingZeros(r,2),":").concat(N.addLeadingZeros(i,2),":").concat(N.addLeadingZeros(n,2),".").concat(N.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),a}(K);e.VASTClient=ce,e.VASTParser=oe,e.VASTTracker=de,Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VAST={})}(this,(function(e){"use strict";function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(e){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}var g=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","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 y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=[],n=A(e);for(var a in!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=w(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING,t)t[a]=N(t[a]);for(var o in n){var s=n[o];"string"==typeof s&&i.push(T(s,t))}return i}function T(e,t){var r=(e=k(e,t)).match(/[^[\]]+(?=])/g);if(!r)return e;var i=r.filter((function(e){return g.indexOf(e)>-1}));return 0===i.length?e:k(e,i=i.reduce((function(e,t){return e[t]=-1,e}),{}))}function k(e,t){var r=e;for(var i in t){var n=t[i];r=r.replace(new RegExp("(?:\\[|%%)(".concat(i,")(?:\\]|%%)"),"g"),n)}return r}function A(e){return Array.isArray(e)?e.map((function(e){return e&&e.hasOwnProperty("url")?e.url:e})):e}function b(e){return/^(https?:\/\/|\/\/)/.test(e)}function R(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}var L={track:function(e,t,r){y(e,t,r).forEach((function(e){"undefined"!=typeof window&&null!==window&&((new Image).src=e)}))},resolveURLTemplates:y,extractURLsFromTemplates:A,filterValidUrlTemplates:function(e){return Array.isArray(e)?e.filter((function(e){return b(e.hasOwnProperty("url")?e.url:e)})):b(e)},containsTemplateObject:R,isTemplateObjectEqual:E,encodeURIComponentRFC3986:N,replaceUrlMacros:T,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce((function(t,r){return t.concat(Array.isArray(r)?e(r):r)}),[])},joinArrayOfUniqueTemplateObjs:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce((function(e,t){return R(t,e)||e.push(t),e}),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:w};function U(e){return-1!==["true","TRUE","True","1"].indexOf(e)}function C(e){if(null==e)return-1;if(L.isNumeric(e))return parseInt(e);var t=e.split(":");if(3!==t.length)return-1;var r=t[2].split("."),i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));var n=parseInt(60*t[1]),a=parseInt(60*t[0]*60);return isNaN(a)||isNaN(n)||isNaN(i)||n>3600||i>60?-1:a+n+i}var I={childByName:function(e,t){var r=e.childNodes;for(var i in r){var n=r[i];if(n.nodeName===t)return n}},childrenByName:function(e,t){var r=[],i=e.childNodes;for(var n in i){var a=i[n];a.nodeName===t&&r.push(a)}return r},resolveVastAdTagURI:function(e,t){if(!t)return e;if(0===e.indexOf("//")){var r=location.protocol;return"".concat(r).concat(e)}if(-1===e.indexOf("://")){var i=t.slice(0,t.lastIndexOf("/"));return"".concat(i,"/").concat(e)}return e},parseBoolean:U,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){var i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){for(var t=e.attributes,r={},i=0;i1){var a=e[n-1];if(a&&a.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){if(e)for(var r in e){var i=e[r];if(i.nodeName&&i.nodeValue&&t.hasOwnProperty(i.nodeName)){var n=i.nodeValue;"boolean"==typeof t[i.nodeName]&&(n=U(n)),t[i.nodeName]=n}}},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[].concat(h(e.viewableImpression),h(t.viewableImpression))),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;var i=(t.creatives||[]).filter((function(e){return e&&"companion"===e.type})),n=i.reduce((function(e,t){return(t.variations||[]).forEach((function(t){(t.companionClickTrackingURLTemplates||[]).forEach((function(t){L.containsTemplateObject(t,e)||e.push(t)}))})),e}),[]);e.creatives=i.concat(e.creatives);var a=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,o=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((function(e){if(t.trackingEvents&&t.trackingEvents[e.type])for(var r in t.trackingEvents[e.type]){var i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(a&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),o&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&n.length&&(e.variations||[]).forEach((function(e){e.companionClickTrackingURLTemplates=L.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,n)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){var s=t.creatives.filter((function(e){var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));s.length&&(e.creatives=e.creatives.concat(s))}}};function x(e,t){var r=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"companion",required:null,variations:[]}}(t);return r.required=e.getAttribute("required")||null,r.variations=I.childrenByName(e,"Companion").map((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(I.parseAttributes(e));t.htmlResources=I.childrenByName(e,"HTMLResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=I.childrenByName(e,"IFrameResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=I.childrenByName(e,"StaticResource").reduce((function(e,t){var r=I.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=I.parseNodeText(I.childByName(e,"AltText"))||null;var r=I.childByName(e,"TrackingEvents");r&&I.childrenByName(r,"Tracking").forEach((function(e){var r=e.getAttribute("event"),i=I.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=I.childrenByName(e,"CompanionClickTracking").map((function(e){return{id:e.getAttribute("id")||null,url:I.parseNodeText(e)}})),t.companionClickThroughURLTemplate=I.parseNodeText(I.childByName(e,"CompanionClickThrough"))||null;var i=I.childByName(e,"AdParameters");return i&&(t.adParameters={value:I.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),r}function S(e,t){var r,i=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(t);i.duration=I.parseDuration(I.parseNodeText(I.childByName(e,"Duration")));var n=e.getAttribute("skipoffset");if(null==n)i.skipDelay=null;else if("%"===n.charAt(n.length-1)&&-1!==i.duration){var a=parseInt(n,10);i.skipDelay=i.duration*(a/100)}else i.skipDelay=I.parseDuration(n);var o=I.childByName(e,"VideoClicks");if(o){var s=I.childByName(o,"ClickThrough");i.videoClickThroughURLTemplate=s?{id:s.getAttribute("id")||null,url:I.parseNodeText(s)}:null,I.childrenByName(o,"ClickTracking").forEach((function(e){i.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})})),I.childrenByName(o,"CustomClick").forEach((function(e){i.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})}))}var l=I.childByName(e,"AdParameters");l&&(i.adParameters={value:I.parseNodeText(l),xmlEncoded:l.getAttribute("xmlEncoded")||null}),I.childrenByName(e,"TrackingEvents").forEach((function(e){I.childrenByName(e,"Tracking").forEach((function(e){var t=e.getAttribute("event"),n=I.parseNodeText(e);if(t&&n){if("progress"===t){if(!(r=e.getAttribute("offset")))return;t="%"===r.charAt(r.length-1)?"progress-".concat(r):"progress-".concat(Math.round(I.parseDuration(r)))}Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(n)}}))})),I.childrenByName(e,"MediaFiles").forEach((function(e){I.childrenByName(e,"MediaFile").forEach((function(e){i.mediaFiles.push(function(e){var t={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,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=I.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);var r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=I.parseBoolean(r));var i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=I.parseBoolean(i));return t}(e))}));var t=I.childByName(e,"InteractiveCreativeFile");t&&(i.interactiveCreativeFile=function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:I.parseBoolean(e.variableDuration),fileURL:null}}(I.parseAttributes(e));return t.fileURL=I.parseNodeText(e),t}(t));var r=I.childByName(e,"ClosedCaptionFiles");r&&I.childrenByName(r,"ClosedCaptionFile").forEach((function(e){var t=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(I.parseAttributes(e));t.fileURL=I.parseNodeText(e),i.closedCaptionFiles.push(t)}));var n,a,o,s=I.childByName(e,"Mezzanine"),l=(n=s,a={},o=!1,["delivery","type","width","height"].forEach((function(e){n&&n.getAttribute(e)?a[e]=n.getAttribute(e):o=!0})),o?null:a);if(l){var c={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};c.id=s.getAttribute("id"),c.fileURL=I.parseNodeText(s),c.delivery=l.delivery,c.codec=s.getAttribute("codec"),c.type=l.type,c.width=parseInt(l.width,10),c.height=parseInt(l.height,10),c.fileSize=parseInt(s.getAttribute("fileSize"),10),c.mediaType=s.getAttribute("mediaType")||"2D",i.mezzanine=c}}));var c=I.childByName(e,"Icons");return c&&I.childrenByName(c,"Icon").forEach((function(e){i.icons.push(function(e){var t={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:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=I.parseDuration(e.getAttribute("offset")),t.duration=I.parseDuration(e.getAttribute("duration")),I.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=I.parseNodeText(e)})),I.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=I.parseNodeText(e)})),I.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=I.parseNodeText(e)}));var r=I.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=I.parseNodeText(I.childByName(r,"IconClickThrough")),I.childrenByName(r,"IconClickTracking").forEach((function(e){t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})}));var i=I.childByName(r,"IconClickFallbackImages");i&&I.childrenByName(i,"IconClickFallbackImage").forEach((function(e){t.iconClickFallbackImages.push({url:I.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=I.parseNodeText(I.childByName(e,"IconViewTracking")),t}(e))})),i}function O(e,t){var r=function(){var e=m(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return{id:e.id,adId:e.adId,sequence:e.sequence,apiFramework:e.apiFramework,type:"nonlinear",variations:[],trackingEvents:{}}}(t);return I.childrenByName(e,"TrackingEvents").forEach((function(e){var t,i;I.childrenByName(e,"Tracking").forEach((function(e){t=e.getAttribute("event"),i=I.parseNodeText(e),t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))}))})),I.childrenByName(e,"NonLinear").forEach((function(e){var t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=I.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=I.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=I.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),I.childrenByName(e,"HTMLResource").forEach((function(e){t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=I.parseNodeText(e)})),I.childrenByName(e,"IFrameResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.iframeResource=I.parseNodeText(e)})),I.childrenByName(e,"StaticResource").forEach((function(e){t.type=e.getAttribute("creativeType")||0,t.staticResource=I.parseNodeText(e)}));var i=I.childByName(e,"AdParameters");i&&(t.adParameters={value:I.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=I.parseNodeText(I.childByName(e,"NonLinearClickThrough")),I.childrenByName(e,"NonLinearClickTracking").forEach((function(e){t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:I.parseNodeText(e)})})),r.variations.push(t)})),r}function D(e){var t=[];return e.forEach((function(e){var r=V(e);r&&t.push(r)})),t}function V(e){if("#comment"===e.nodeName)return null;var t,r={name:null,value:null,attributes:{},children:[]},i=e.attributes,n=e.childNodes;if(r.name=e.nodeName,e.attributes)for(var a in i)if(i.hasOwnProperty(a)){var o=i[a];o.nodeName&&o.nodeValue&&(r.attributes[o.nodeName]=o.nodeValue)}for(var s in n)if(n.hasOwnProperty(s)){var l=V(n[s]);l&&r.children.push(l)}if(0===r.children.length||1===r.children.length&&["#cdata-section","#text"].indexOf(r.children[0].name)>=0){var c=I.parseNodeText(e);""!==c&&(r.value=c),r.children=[]}return null===(t=r).value&&0===Object.keys(t.attributes).length&&0===t.children.length?null:r}function P(e){var t=[];return e.forEach((function(e){var r,i={id:e.getAttribute("id")||null,adId:B(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},n=[];I.childrenByName(e,"UniversalAdId").forEach((function(e){var t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:I.parseNodeText(e)};n.push(t)}));var a=I.childByName(e,"CreativeExtensions");for(var o in a&&(r=D(I.childrenByName(a,"CreativeExtension"))),e.childNodes){var s=e.childNodes[o],l=void 0;switch(s.nodeName){case"Linear":l=S(s,i);break;case"NonLinearAds":l=O(s,i);break;case"CompanionAds":l=x(s,i)}l&&(n&&(l.universalAdIds=n),r&&(l.creativeExtensions=r),t.push(l))}})),t}function B(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}var F={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function M(e,t){if(F[e.nodeName]&&F[e.nodeName].attributes){var r=F[e.nodeName].attributes.filter((function(t){return!e.getAttribute(t)}));r.length>0&&q({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}}function j(e,t,r){var i=F[e.nodeName],n=!r&&"Wrapper"!==e.nodeName;if(i&&!n){if(i.subElements){var a=i.subElements.filter((function(t){return!I.childByName(e,t)}));a.length>0&&q({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:a},t)}if(r&&i.oneOfinLineResources)i.oneOfinLineResources.some((function(t){return I.childByName(e,t)}))||q({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}}function W(e){return e.children&&0!==e.children.length}function q(e,t){var r=e.name,i=e.parentName,n=e.attributes,a=e.subElements,o=e.oneOfResources,s="Element '".concat(r,"'");t("VAST-warning",{message:s+=n?" missing required attribute(s) '".concat(n.join(", "),"' "):a?" missing required sub element(s) '".concat(a.join(", "),"' "):o?" must provide one of the following '".concat(o.join(", "),"' "):" is empty",parentElement:i,specVersion:4.1})}var H={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),M(t,r),W(t)){j(t,r,i);for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{},i=r.allowMultipleAds,n=r.followAdditionalWrappers,a=e.childNodes;for(var o in a){var s=a[o];if(-1!==["Wrapper","InLine"].indexOf(s.nodeName)&&("Wrapper"!==s.nodeName||!1!==n)){if(I.copyNodeAttribute("id",e,s),I.copyNodeAttribute("sequence",e,s),I.copyNodeAttribute("adType",e,s),"Wrapper"===s.nodeName)return{ad:Y(s,t),type:"WRAPPER"};if("InLine"===s.nodeName)return{ad:G(s,t,{allowMultipleAds:i}),type:"INLINE"}}}}function G(e,t){return!1===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allowMultipleAds&&e.getAttribute("sequence")?null:z(e,t)}function z(e,t){var r=[];t&&H.verifyRequiredValues(e,t);var i,n,a=e.childNodes,o=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(I.parseAttributes(e));for(var s in a){var l=a[s];switch(l.nodeName){case"Error":o.errorURLTemplates.push(I.parseNodeText(l));break;case"Impression":o.impressionURLTemplates.push({id:l.getAttribute("id")||null,url:I.parseNodeText(l)});break;case"Creatives":o.creatives=P(I.childrenByName(l,"Creative"));break;case"Extensions":var c=I.childrenByName(l,"Extension");o.extensions=D(c),o.adVerifications.length||(r=K(c));break;case"AdVerifications":o.adVerifications=X(I.childrenByName(l,"Verification"));break;case"AdSystem":o.system={value:I.parseNodeText(l),version:l.getAttribute("version")||null};break;case"AdTitle":o.title=I.parseNodeText(l);break;case"AdServingId":o.adServingId=I.parseNodeText(l);break;case"Category":o.categories.push({authority:l.getAttribute("authority")||null,value:I.parseNodeText(l)});break;case"Expires":o.expires=parseInt(I.parseNodeText(l),10);break;case"ViewableImpression":o.viewableImpression.push((n=void 0,n=function(e,t){var r=I.parseNodeText(t);return r&&e.push(r),e},{id:(i=l).getAttribute("id")||null,viewable:I.childrenByName(i,"Viewable").reduce(n,[]),notViewable:I.childrenByName(i,"NotViewable").reduce(n,[]),viewUndetermined:I.childrenByName(i,"ViewUndetermined").reduce(n,[])}));break;case"Description":o.description=I.parseNodeText(l);break;case"Advertiser":o.advertiser={id:l.getAttribute("id")||null,value:I.parseNodeText(l)};break;case"Pricing":o.pricing={value:I.parseNodeText(l),model:l.getAttribute("model")||null,currency:l.getAttribute("currency")||null};break;case"Survey":o.survey={value:I.parseNodeText(l),type:l.getAttribute("type")||null};break;case"BlockedAdCategories":o.blockedAdCategories.push({authority:l.getAttribute("authority")||null,value:I.parseNodeText(l)})}}return r.length&&(o.adVerifications=o.adVerifications.concat(r)),o}function Y(e,t){var r=z(e,t),i=e.getAttribute("followAdditionalWrappers"),n=e.getAttribute("allowMultipleAds"),a=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||I.parseBoolean(i),r.allowMultipleAds=!!n&&I.parseBoolean(n),r.fallbackOnNoAd=a?I.parseBoolean(a):null;var o=I.childByName(e,"VASTAdTagURI");if(o?r.nextWrapperURL=I.parseNodeText(o):(o=I.childByName(e,"VASTAdTagURL"))&&(r.nextWrapperURL=I.parseNodeText(I.childByName(o,"URL"))),r.creatives.forEach((function(e){if(-1!==["linear","nonlinear"].indexOf(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});var t=function(t){var i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((function(i){r.trackingEvents[e.type][t].push(i)}))};for(var i in e.trackingEvents)t(i)}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((function(e){r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((function(e){r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function X(e){var t=[];return e.forEach((function(e){var r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=e.childNodes;for(var n in I.assignAttributes(e.attributes,r),i){var a=i[n];switch(a.nodeName){case"JavaScriptResource":case"ExecutableResource":r.resource=I.parseNodeText(a),I.assignAttributes(a.attributes,r);break;case"VerificationParameters":r.parameters=I.parseNodeText(a)}}var o=I.childByName(e,"TrackingEvents");o&&I.childrenByName(o,"Tracking").forEach((function(e){var t=e.getAttribute("event"),i=I.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}function K(e){var t=null,r=[];return e.some((function(e){return t=I.childByName(e,"AdVerifications")})),t&&(r=X(I.childrenByName(t,"Verification"))),r}var Q=function(){function e(){n(this,e),this._handlers=[]}return o(e,[{key:"on",value:function(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(i(t)));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(i(e)));return this._handlers.push({event:e,handler:t}),this}},{key:"once",value:function(e,t){return this.on(e,function(e,t,r){var i={fired:!1,wrapFn:void 0};function n(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e).apply(void 0,arguments))}return i.wrapFn=n,n}(this,e,t))}},{key:"off",value:function(e,t){return this._handlers=this._handlers.filter((function(r){return r.event!==e||r.handler!==t})),this}},{key:"emit",value:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i2?r-2:0),n=2;n1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return new Promise((function(a,o){t.URLTemplateFilters.forEach((function(t){e=t(e)}));var s=Date.now();t.emit("VAST-resolving",{url:e,previousUrl:i,wrapperDepth:r,maxWrapperDepth:t.maxWrapperDepth,timeout:t.fetchingOptions.timeout,wrapperAd:n}),t.urlHandler.get(e,t.fetchingOptions,(function(n,l){var c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},u=Math.round(Date.now()-s),d=Object.assign({url:e,previousUrl:i,wrapperDepth:r,error:n,duration:u},c);t.emit("VAST-resolved",d),ae(c.byteLength,u),n?o(n):a(l)}))}))}},{key:"initParsingStatus",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errorURLTemplates=[],this.fetchingOptions={timeout:e.timeout||J,withCredentials:e.withCredentials},this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.remainingAds=[],this.rootErrorURLTemplates=[],this.rootURL="",this.urlHandler=e.urlHandler||e.urlhandler||re,this.vastVersion=null,ae(e.byteLength,e.requestDuration)}},{key:"getRemainingAds",value:function(e){var t=this;if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));var r=e?L.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then((function(e){return t.buildVASTResponse(e)}))}},{key:"getAndParseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),this.URLTemplateFilters.forEach((function(t){e=t(e)})),this.rootURL=e,this.fetchVAST(e).then((function(i){return r.previousUrl=e,r.isRootVAST=!0,r.url=e,t.parse(i,r).then((function(e){return t.buildVASTResponse(e)}))}))}},{key:"parseVAST",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then((function(e){return t.buildVASTResponse(e)}))}},{key:"buildVASTResponse",value:function(e){var t,r={ads:(t={ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion}).ads||[],errorURLTemplates:t.errorURLTemplates||[],version:t.version||null};return this.completeWrapperResolving(r),r}},{key:"parseVastXml",value:function(e,t){var r=t.isRootVAST,i=void 0!==r&&r,n=t.url,a=void 0===n?null:n,o=t.wrapperDepth,s=void 0===o?0:o,l=t.allowMultipleAds,c=t.followAdditionalWrappers;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:a,wrapperDepth:s}),new Error("Invalid VAST XMLDocument");var u=[],d=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");for(var h in i&&p&&(this.vastVersion=p),d){var v=d[h];if("Error"===v.nodeName){var f=I.parseNodeText(v);i?this.rootErrorURLTemplates.push(f):this.errorURLTemplates.push(f)}else if("Ad"===v.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)l=!0;else if(!1===l&&u.length>1)break;var m=_(v,this.emit.bind(this),{allowMultipleAds:l,followAdditionalWrappers:c});m.ad?(u.push(m.ad),this.emit("VAST-ad-parsed",{type:m.type,url:a,wrapperDepth:s,adIndex:u.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return u}},{key:"parse",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.url,i=void 0===r?null:r,n=t.resolveAll,a=void 0===n||n,o=t.wrapperSequence,s=void 0===o?null:o,l=t.previousUrl,c=void 0===l?null:l,u=t.wrapperDepth,d=void 0===u?0:u,p=t.isRootVAST,h=void 0!==p&&p,v=t.followAdditionalWrappers,f=t.allowMultipleAds,m=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&h&&(f=!0);try{m=this.parseVastXml(e,{isRootVAST:h,url:i,wrapperDepth:d,allowMultipleAds:f,followAdditionalWrappers:v})}catch(e){return Promise.reject(e)}return 1===m.length&&null!=s&&(m[0].sequence=s),!1===a&&(this.remainingAds=I.splitVAST(m),m=this.remainingAds.shift()),this.resolveAds(m,{wrapperDepth:d,previousUrl:c,url:i})}},{key:"resolveAds",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,i=r.wrapperDepth,n=r.previousUrl,a=r.url,o=[];return n=a,t.forEach((function(t){var r=e.resolveWrappers(t,i,n);o.push(r)})),Promise.all(o).then((function(t){var r=L.flatten(t);if(!r&&e.remainingAds.length>0){var o=e.remainingAds.shift();return e.resolveAds(o,{wrapperDepth:i,previousUrl:n,url:a})}return r}))}},{key:"resolveWrappers",value:function(e,t,r){var i=this;return new Promise((function(n){var a;if(t++,!e.nextWrapperURL)return delete e.nextWrapperURL,n(e);if(t>=i.maxWrapperDepth)return e.errorCode=302,delete e.nextWrapperURL,n(e);e.nextWrapperURL=I.resolveVastAdTagURI(e.nextWrapperURL,r),i.URLTemplateFilters.forEach((function(t){e.nextWrapperURL=t(e.nextWrapperURL)}));var o=null!==(a=i.parsingOptions.allowMultipleAds)&&void 0!==a?a:e.allowMultipleAds,s=e.sequence;i.fetchVAST(e.nextWrapperURL,t,r,e).then((function(a){return i.parse(a,{url:e.nextWrapperURL,previousUrl:r,wrapperSequence:s,wrapperDepth:t,followAdditionalWrappers:e.followAdditionalWrappers,allowMultipleAds:o}).then((function(t){if(delete e.nextWrapperURL,0===t.length)return e.creatives=[],n(e);t.forEach((function(t){t&&I.mergeWrapperAdData(t,e)})),n(t)}))})).catch((function(t){e.errorCode=301,e.errorMessage=t.message,n(e)}))}))}},{key:"completeWrapperResolving",value:function(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(var t=e.ads.length-1;t>=0;t--){var r=e.ads[t];(r.errorCode||0===r.creatives.length)&&(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}]),r}(Q),le=null,ce={data:{},length:0,getItem:function(e){return this.data[e]},setItem:function(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem:function(e){delete this.data[e],this.length=Object.keys(this.data).length},clear:function(){this.data={},this.length=0}},ue=function(){function e(){n(this,e),this.storage=this.initStorage()}return o(e,[{key:"initStorage",value:function(){if(le)return le;try{le="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){le=null}return le&&!this.isStorageDisabled(le)||(le=ce).clear(),le}},{key:"isStorageDisabled",value:function(e){var t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}},{key:"getItem",value:function(e){return this.storage.getItem(e)}},{key:"setItem",value:function(e,t){return this.storage.setItem(e,t)}},{key:"removeItem",value:function(e){return this.storage.removeItem(e)}},{key:"clear",value:function(){return this.storage.clear()}}]),e}(),de=function(){function e(t,r,i){n(this,e),this.cappingFreeLunch=t||0,this.cappingMinimumTimeInterval=r||0,this.defaultOptions={withCredentials:!1,timeout:0},this.vastParser=new se,this.storage=i||new ue,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}return o(e,[{key:"getParser",value:function(){return this.vastParser}},{key:"lastSuccessfulAd",get:function(){return this.storage.getItem("vast-client-last-successful-ad")},set:function(e){this.storage.setItem("vast-client-last-successful-ad",e)}},{key:"totalCalls",get:function(){return this.storage.getItem("vast-client-total-calls")},set:function(e){this.storage.setItem("vast-client-total-calls",e)}},{key:"totalCallsTimeout",get:function(){return this.storage.getItem("vast-client-total-calls-timeout")},set:function(e){this.storage.setItem("vast-client-total-calls-timeout",e)}},{key:"hasRemainingAds",value:function(){return this.vastParser.remainingAds.length>0}},{key:"getNextAds",value:function(e){return this.vastParser.getRemainingAds(e)}},{key:"get",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Date.now();return(r=Object.assign({},this.defaultOptions,r)).hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout=t.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(t.totalCalls,"/").concat(t.cappingFreeLunch)));var o=i-t.lastSuccessfulAd;if(o<0)t.lastSuccessfulAd=0;else if(o3&&void 0!==arguments[3]?arguments[3]:null,l=arguments.length>4&&void 0!==arguments[4]&&arguments[4];for(var c in n(this,a),(o=t.call(this)).ad=r,o.creative=i,o.variation=s,o.muted=l,o.impressed=!1,o.skippable=!1,o.trackingEvents={},o.lastPercentage=0,o._alreadyTriggeredQuartiles={},o.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"],o.creative.trackingEvents){var u=o.creative.trackingEvents[c];o.trackingEvents[c]=u.slice(0)}return!function(e){return"linear"===e.type}(o.creative)?o._initVariationTracking():o._initLinearTracking(),e&&o.on("start",(function(){e.lastSuccessfulAd=Date.now()})),o}return o(a,[{key:"_initLinearTracking",value:function(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}},{key:"_initVariationTracking",value:function(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(var e in this.variation.trackingEvents){var t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}},{key:"setDuration",value:function(e){L.isValidTimeValue(e)&&(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100})}},{key:"setProgress",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(L.isValidTimeValue(e)&&"object"===i(r)){var n=this.skipDelay||-1;if(-1===n||this.skippable||(n>e?this.emit("skip-countdown",n-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){var a=Math.round(e/this.assetDuration*100),o=[];if(e>0){o.push("start");for(var s=this.lastPercentage;s1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e)}},{key:"setPaused",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e)}},{key:"setFullscreen",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e)}},{key:"setExpand",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"===i(t)&&(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e)}},{key:"setSkipDelay",value:function(e){L.isValidTimeValue(e)&&(this.skipDelay=e)}},{key:"trackImpression",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})))}},{key:"trackViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewable,t)}))}},{key:"trackNotViewableImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.notViewable,t)}))}},{key:"trackUndeterminedImpression",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(t)&&this.ad.viewableImpression.forEach((function(r){e.trackURLs(r.viewUndetermined,t)}))}},{key:"error",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"===i(e)&&"boolean"==typeof t&&this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t})}},{key:"errorWithCode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t&&(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead"))}},{key:"complete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("complete",{macros:e})}},{key:"notUsed",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&(this.track("notUsed",{macros:e}),this.trackingEvents=[])}},{key:"otherAdInteraction",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("otherAdInteraction",{macros:e})}},{key:"acceptInvitation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("acceptInvitation",{macros:e})}},{key:"adExpand",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adExpand",{macros:e})}},{key:"adCollapse",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("adCollapse",{macros:e})}},{key:"minimize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("minimize",{macros:e})}},{key:"verificationNotExecuted",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&"object"===i(t)){if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");var r=this.ad.adVerifications.find((function(t){return t.vendor===e}));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));var n=r.trackingEvents;if(n&&n.verificationNotExecuted){var a=n.verificationNotExecuted;this.trackURLs(a,t),this.emit("verificationNotExecuted",{trackingURLTemplates:a})}}}},{key:"overlayViewDuration",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"===i(t)&&(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t}))}},{key:"close",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track(this.linear?"closeLinear":"close",{macros:e})}},{key:"skip",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("skip",{macros:e})}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"===i(e)&&this.track("loaded",{macros:e})}},{key:"click",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((null===e||"string"==typeof e)&&"object"===i(t)){this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);var n=this.clickThroughURLTemplate||e,a=r({},t);if(n){this.progress&&(a.ADPLAYHEAD=this.progressFormatted());var o=L.resolveURLTemplates([n],a)[0];this.emit("clickthrough",o)}}}},{key:"track",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.macros,n=void 0===r?{}:r,a=t.once,o=void 0!==a&&a;if("object"===i(n)){"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");var s=this.trackingEvents[e],l=this.emitAlwaysEvents.indexOf(e)>-1;s?(this.emit(e,{trackingURLTemplates:s}),this.trackURLs(s,n)):l&&this.emit(e,null),o&&(delete this.trackingEvents[e],l&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}}},{key:"trackURLs",value:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=L.filterValidUrlTemplates(e),o=r({},i);this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(o.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(o.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(o.UNIVERSALADID=this.creative.universalAdIds.map((function(e){return e.idRegistry.concat(" ",e.value)})).join(",")),this.ad&&(this.ad.sequence&&(o.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(o.ADTYPE=this.ad.adType),this.ad.adServingId&&(o.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(o.ADCATEGORIES=this.ad.categories.map((function(e){return e.value})).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(o.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories)),L.track(a,o,n)}},{key:"convertToTimecode",value:function(e){if(!L.isValidTimeValue(e))return"";var t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),n=Math.floor(t/1e3%60),a=Math.floor(t%1e3);return"".concat(L.addLeadingZeros(r,2),":").concat(L.addLeadingZeros(i,2),":").concat(L.addLeadingZeros(n,2),".").concat(L.addLeadingZeros(a,3))}},{key:"progressFormatted",value:function(){return this.convertToTimecode(this.progress)}}]),a}(Q);e.VASTClient=de,e.VASTParser=se,e.VASTTracker=pe,e.parseDuration=C,Object.defineProperty(e,"__esModule",{value:!0})}));