@newrelic/video-core 5.0.2 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +13 -0
  3. package/dist/cjs/browser/index.js +1 -1
  4. package/dist/cjs/browser/index.js.LICENSE.txt +1 -1
  5. package/dist/cjs/browser/index.js.map +1 -1
  6. package/dist/cjs/index.js +1 -1
  7. package/dist/cjs/index.js.LICENSE.txt +1 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/vega/index.js +1 -1
  10. package/dist/cjs/vega/index.js.LICENSE.txt +1 -1
  11. package/dist/cjs/vega/index.js.map +1 -1
  12. package/dist/esm/browser/index.js +1 -1
  13. package/dist/esm/browser/index.js.LICENSE.txt +1 -1
  14. package/dist/esm/browser/index.js.map +1 -1
  15. package/dist/esm/index.js +1 -1
  16. package/dist/esm/index.js.LICENSE.txt +1 -1
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/esm/vega/index.js +1 -1
  19. package/dist/esm/vega/index.js.LICENSE.txt +1 -1
  20. package/dist/esm/vega/index.js.map +1 -1
  21. package/dist/types/browser/agent.d.ts +46 -0
  22. package/dist/types/browser/harvestScheduler.d.ts +125 -0
  23. package/dist/types/browser/index.d.ts +34 -0
  24. package/dist/types/chrono.d.ts +52 -0
  25. package/dist/types/connectedDevice/connectedDeviceAgent.d.ts +63 -0
  26. package/dist/types/connectedDevice/connectedDeviceConstants.d.ts +51 -0
  27. package/dist/types/connectedDevice/connectedDeviceHarvester.d.ts +198 -0
  28. package/dist/types/connectedDevice/index.d.ts +30 -0
  29. package/dist/types/constants.d.ts +30 -0
  30. package/dist/types/core.d.ts +54 -0
  31. package/dist/types/emitter.d.ts +42 -0
  32. package/dist/types/eventAggregator.d.ts +97 -0
  33. package/dist/types/index.d.ts +33 -0
  34. package/dist/types/log.d.ts +61 -0
  35. package/dist/types/obfuscate.d.ts +13 -0
  36. package/dist/types/optimizedHttpClient.d.ts +83 -0
  37. package/dist/types/recordEvent.d.ts +30 -0
  38. package/dist/types/retryQueueHandler.d.ts +46 -0
  39. package/dist/types/tracker.d.ts +176 -0
  40. package/dist/types/utils/eventBuilder.d.ts +69 -0
  41. package/dist/types/utils/harvestTimer.d.ts +45 -0
  42. package/dist/types/utils/index.d.ts +38 -0
  43. package/dist/types/utils/qoeFilters.d.ts +88 -0
  44. package/dist/types/videoConfiguration.d.ts +90 -0
  45. package/dist/types/videotracker.d.ts +366 -0
  46. package/dist/types/videotrackerstate.d.ts +228 -0
  47. package/dist/umd/nrvideo.min.js +1 -1
  48. package/dist/umd/nrvideo.min.js.LICENSE.txt +1 -1
  49. package/dist/umd/nrvideo.min.js.map +1 -1
  50. package/package.json +14 -2
  51. package/src/browser/{agent.js → agent.ts} +21 -16
  52. package/src/browser/{harvestScheduler.js → harvestScheduler.ts} +51 -24
  53. package/src/{chrono.js → chrono.ts} +29 -24
  54. package/src/connectedDevice/{connectedDeviceAgent.js → connectedDeviceAgent.ts} +14 -10
  55. package/src/connectedDevice/{connectedDeviceConstants.js → connectedDeviceConstants.ts} +5 -3
  56. package/src/connectedDevice/{connectedDeviceHarvester.js → connectedDeviceHarvester.ts} +71 -34
  57. package/src/constants.ts +62 -0
  58. package/src/{core.js → core.ts} +31 -18
  59. package/src/{emitter.js → emitter.ts} +16 -5
  60. package/src/{eventAggregator.js → eventAggregator.ts} +33 -19
  61. package/src/global.d.ts +25 -0
  62. package/src/{log.js → log.ts} +23 -17
  63. package/src/{obfuscate.js → obfuscate.ts} +6 -1
  64. package/src/{optimizedHttpClient.js → optimizedHttpClient.ts} +37 -13
  65. package/src/{recordEvent.js → recordEvent.ts} +11 -9
  66. package/src/{retryQueueHandler.js → retryQueueHandler.ts} +17 -12
  67. package/src/{tracker.js → tracker.ts} +56 -23
  68. package/src/utils/{eventBuilder.js → eventBuilder.ts} +31 -14
  69. package/src/utils/{harvestTimer.js → harvestTimer.ts} +21 -4
  70. package/src/utils/{index.js → index.ts} +14 -14
  71. package/src/utils/{qoeFilters.js → qoeFilters.ts} +19 -8
  72. package/src/{videoConfiguration.js → videoConfiguration.ts} +44 -10
  73. package/src/{videotracker.js → videotracker.ts} +119 -78
  74. package/src/{videotrackerstate.js → videotrackerstate.ts} +113 -49
  75. package/src/constants.js +0 -63
  76. /package/src/browser/{index.js → index.ts} +0 -0
  77. /package/src/connectedDevice/{index.js → index.ts} +0 -0
  78. /package/src/{index.js → index.ts} +0 -0
package/dist/cjs/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- (()=>{"use strict";const e={d:(t,i)=>{if(Array.isArray(i))for(var s=0;s<i.length;){var r=i[s++],a=i[s++];e.o(t,r)?0===a&&s++:0===a?Object.defineProperty(t,r,{enumerable:!0,value:i[s++]}):Object.defineProperty(t,r,{enumerable:!0,get:a})}else for(var r in i)e.o(i,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:i[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{connectedDeviceAnalyticsHarvester:()=>se,default:()=>re,getRegisteredHarvester:()=>p,videoAnalyticsHarvester:()=>ee});class i{static error(...e){s(e,i.Levels.ERROR,"darkred")}static warn(...e){s(e,i.Levels.WARNING,"darkorange")}static notice(...e){s([].slice.call(arguments),i.Levels.NOTICE,"darkcyan")}static debug(...e){s(e,i.Levels.DEBUG,"indigo")}static debugCommonVideoEvents(e,t,s){try{if(i.level<=i.Levels.DEBUG){s=s||function(e){i.debug("Event: "+e.type)};var r=["canplay","buffering","waiting","ended","play","playing","pause","resume","error","abort","seek","seeking","seeked","stalled","dispose","loadeddata","loadstart","loadedmetadata"];t&&(null===t[0]?(t.shift(),r=t):r=r.concat(t));for(var a=0;a<r.length;a++)"function"==typeof e?e.call(window,r[a],s):e.on?e.on(r[a],s):e.addEventListener?e.addEventListener(r[a],s):e.addEventHandler?e.addEventHandler(r[a],s):i.warn("debugCommonVideoEvents: No common listener function found for ",e)}}catch(e){i.warn(e)}}}function s(e,t,s){t=t||i.Levels.NOTICE,s=s||"darkcyan";var n,o,h,l,d,c,u=i.prefix;(i.includeTime&&(u+=(n=new Date,o=("0"+n.getDate()).slice(-2),h=("0"+n.getMinutes()).slice(-2),l=("0"+n.getSeconds()).slice(-2),d=("00"+n.getMilliseconds()).slice(-3),"["+o+":"+h+":"+l+"."+d+"] ")),u+=function(e){return a[e]}(t)+":",i.level<=t&&t!==i.Levels.SILENT)&&(!i.colorful||"undefined"!=typeof document&&document.documentMode?r(e,u):(c=t===i.Levels.ERROR&&console.error?console.error:t===i.Levels.WARNING&&console.warn?console.warn:t===i.Levels.DEBUG&&console.debug&&null==window.cast?console.debug:console.log,u="%c"+u,e.splice(0,0,u,"color: "+s),c.apply(console,e)))}function r(e,t){if(e instanceof Array)for(var i in e)r(e[i],t);else"string"==typeof e?console.log(t+" "+e):(console.log(t+"↵"),console.log(e))}i.Levels={SILENT:5,ERROR:4,WARNING:3,NOTICE:2,DEBUG:1,ALL:0},i.level=i.Levels.ERROR,i.colorful=!0,i.includeTime=!0,i.prefix="[nrvideo]";const a={4:"e",3:"w",2:"n",1:"d"};!function(){if("undefined"!=typeof window&&window.location&&window.location.search){var e=/\?.*&*nrvideo-debug=(.+)/i.exec(window.location.search);null!==e&&("true"===e[1]?i.level=i.Levels.ALL:i.level=e[1]),null!==/\?.*&*nrvideo-colors=false/i.exec(window.location.search)&&(i.colorful=!1)}}();const n=i;class o{}o.AdPositions={PRE:"pre",MID:"mid",POST:"post"},o.COLLECTOR={US:["bam.nr-data.net","bam-cell.nr-data.net"],EU:"bam.eu01.nr-data.net",JP:"bam.jp.nr-data.net",Staging:"staging-bam-cell.nr-data.net",GOV:"gov-bam.nr-data.net"},o.VALID_EVENT_TYPES=["VideoAction","VideoAdAction","VideoErrorAction","VideoCustomAction"],o.MAX_PAYLOAD_SIZE=1048576,o.MAX_BEACON_SIZE=61440,o.MAX_EVENTS_PER_BATCH=1e3,o.INTERVAL=1e4,o.DEFAULT_QOE_INTERVAL_FACTOR=2,o.QOE_KPI_KEYS=["startupTime","peakBitrate","averageBitrate","totalPlaytime","totalRebufferingTime","rebufferingRatio","hadStartupError","hadPlaybackError","numberOfErrors"],o.QOE_AGGREGATE_KEYS=["coreVersion","instrumentation.name","instrumentation.provider","instrumentation.version","isBackgroundEvent","playerName","playerVersion","src","viewId","viewSession","contentIsAutoplayed","contentIsMuted","contentRenditionHeight","contentRenditionWidth","contentSrc","numberOfVideos","pageUrl","trackerName","trackerVersion","contentDuration","contentPlayrate","contentPlayhead","contentPreload","elapsedTime","contentTitle","contentId","contentIsLive","deviceType","deviceGroup","deviceManufacturer","deviceModel","deviceName","deviceSize","deviceUuid","contentRenditionName","contentIsFullscreen","contentCdn","contentFps","asnOrganization","asnLongitude","asnLatitude","asn","timeSinceRequested","timeSinceStarted"];const h=o,l="5.0.2";const d=class{on(e,t){if(this._listeners=this._listeners||{},"function"==typeof t)return this._listeners[e]=this._listeners[e]||[],this._listeners[e].push(t),this}off(e,t){if(this._listeners=this._listeners||{},this._listeners[e]){var i=this._listeners[e].indexOf(t);-1!==i&&this._listeners[e].splice(i,1)}return this}emit(e,t,i){return this._listeners=this._listeners||{},i=i||{},Array.isArray(this._listeners[t])&&this._listeners[t].forEach(s=>{s.call(this,{eventType:e,type:t,data:i,target:this})}),Array.isArray(this._listeners["*"])&&this._listeners["*"].forEach(s=>{s.call(this,{eventType:e,type:t,data:i,target:this})}),this}};class c{constructor(){this.reset()}reset(){this.startTime=0,this.stopTime=0,this.accumulator=0,this.offset=0}getDeltaTime(){return this.startTime?this.offset+((new Date).getTime()-this.startTime):null}start(){this.startTime=(new Date).getTime(),this.stopTime=0}stop(){return this.stopTime=(new Date).getTime(),this.startTime<this.stopTime&&(this.accumulator+=this.stopTime-this.startTime),this.getDeltaTime()}getDuration(){return this.stopTime?this.accumulator+this.offset:this.accumulator+(this.getDeltaTime()??0)}clone(){var e=new c;return e.startTime=this.startTime,e.stopTime=this.stopTime,e.offset=this.offset,e.accumulator=this.accumulator,e}}const u=c;class f extends d{constructor(e){super(),this.customData={},this.heartbeat=null,this.parentTracker=null,this._trackerReadyChrono=new u,this._trackerReadyChrono.start(),this._actionTable=h.ACTION_TABLE,this._actionAdTable=h.ACTION_AD_TABLE,e=e||{},this.setOptions(e)}setOptions(e){e&&(e.parentTracker&&(this.parentTracker=e.parentTracker),e.customData&&(this.customData=e.customData),e.heartbeat&&(this.heartbeat=e.heartbeat))}dispose(){this.unregisterListeners()}registerListeners(){}unregisterListeners(){}getHeartbeat(){return this.state._isAd?2e3:this.heartbeat?this.heartbeat:this.parentTracker&&this.parentTracker.heartbeat?this.parentTracker.heartbeat:3e4}startHeartbeat(){this._heartbeatInterval=setInterval(this.sendHeartbeat.bind(this),Math.max(this.getHeartbeat(),2e3))}stopHeartbeat(){this._heartbeatInterval&&clearInterval(this._heartbeatInterval)}sendHeartbeat(e){this.sendVideoAction(f.Events.HEARTBEAT,e)}getAttributes(e,t){(e=e||{}).trackerName=this.getTrackerName(),e.trackerVersion=this.getTrackerVersion(),e.coreVersion=l,e.timeSinceTrackerReady=this._trackerReadyChrono.getDeltaTime();for(let t in this.customData)e[t]=this.customData[t];return null!=document.hidden&&(e.isBackgroundEvent=document.hidden),e}getTrackerVersion(){return l}getTrackerName(){return"base-tracker"}sendVideoAction(e,t){this.emit("VideoAction",e,this.getAttributes(t))}sendVideoAdAction(e,t){this.emit("VideoAdAction",e,this.getAttributes(t))}sendVideoErrorAction(e,t){let i=this.isAd()?"adError":"videoError";this.emit("VideoErrorAction",e,this.getAttributes(t,i))}sendVideoCustomAction(e,t){this.emit("VideoCustomAction",e,this.getAttributes(t,"customAction"))}setHarvestInterval(e){const t=this.getHarvester?.();if(t)try{t.setHarvestInterval(e)}catch(e){return void n.error("Failed to set harvest interval:",e.message)}else n.error("Tracker has no harvester; setHarvestInterval ignored")}getHarvester(){return null}}f.Events={HEARTBEAT:"HEARTBEAT",QOE_AGGREGATE:"QOE_AGGREGATE"};const g=f;function m(e){try{return JSON.stringify(e,(()=>{const e=new WeakSet;return(t,i)=>{if("object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})())??""}catch(e){return n.error("Error stringifying value:",e.message),""}}function v(e){if("string"==typeof e&&e.length)return e.length;if("object"==typeof e){if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer&&e.byteLength)return e.byteLength;if("undefined"!=typeof Blob&&e instanceof Blob&&e.size)return e.size;if(!("undefined"!=typeof FormData&&e instanceof FormData))try{return m(e).length}catch(e){return}}}function T(e,t,i,{addTimeSinceLoad:s=!1}={}){const{appName:r,applicationID:a}=i,{qoe:n,...o}=t,l=n?{...n}:{},d={...a?{}:{appName:r},timestamp:Date.now(),...s?{timeSinceLoad:"undefined"!=typeof window&&window.performance?window.performance.now()/1e3:null}:{}},c={...o,eventType:e,...d};let u=null;if("VideoAction"===e){const e=(f=h.QOE_AGGREGATE_KEYS,m=t,f&&Array.isArray(f)&&0!==f.length?m&&"object"==typeof m?f.reduce((e,t)=>(t in m&&(e[t]=m[t]),e),{}):{}:m);u={eventType:"VideoAction",actionName:g.Events.QOE_AGGREGATE,qoeAggregateVersion:"1.0.0",...l,...e,...d}}var f,m;return{eventObject:c,qoeEventObject:u}}const E=Object.create(null);function A(e,t){E[e]=t}function p(e){return E[e]}function y(e,t={}){try{if(!h.VALID_EVENT_TYPES.includes(e))return n.warn("Invalid event type provided to recordEvent",{eventType:e}),!1;const i="Vega"===t.src,s=i?"Vega":"Browser",r="undefined"!=typeof window?window:void 0,a=i?globalThis.__NRVIDEO_CD__?.info:r?.NRVIDEO?.info;if(!a)return;const o=E[s];if(!o)return n.warn("No harvester registered for routing key",{routingKey:s}),!1;return function(e,t,i,s,r,{addTimeSinceLoad:a=!1}={}){if(!s)return!1;const{eventObject:n,qoeEventObject:o}=T(e,t,i,{addTimeSinceLoad:a}),h=s.addEvent(n);return o&&r?h&&s.addEvent(o):h}(e,t,a,o,i?globalThis.__NRVIDEO_CD__?.config?.qoeAggregate:r?.NRVIDEO?.config?.qoeAggregate,{addTimeSinceLoad:!i})}catch(e){return n.error("Failed to record event:",e.message),!1}}const S={us:"https://mobile-collector.newrelic.com/mobile",eu:"https://mobile-collector.eu01.nr-data.net/mobile",staging:"https://staging-mobile-collector.newrelic.com/mobile",gov:"https://gov-mobile-collector.newrelic.com/mobile",jp:"https://mobile-collector.jp.nr-data.net/mobile"},_=[["newrelic_mobile_example","1.1","com.newrelic.newrelic_mobile_example"],["Android","14","sdk_gphone64_arm64","AndroidAgent","7.4.0-alpha01","b797aee6-aa69-4879-9ba3-1f4aed1a7777","","","Google",{size:"normal",platform:"Flutter",platformVersion:"1.0.8"}]],B=["Vega","1.0","VegaDevice","VegaAgent","1.0.0","00000000-0000-0000-0000-000000000000","","","Amazon",{size:"normal",platform:"Native",platformVersion:"1.0.0"}],b={osBuild:"1",osName:"Vega",platform:"Native",appBuild:"1",architecture:"aarch64"},{COLLECTOR:R}=h;class D{setConfiguration(e,t,i){return!!("Vega"===i?this.validateVegaFields(e):this.validateRequiredFields(e))&&(!!this.validateConfigFields(t)&&(this.initializeGlobalConfig(e,t,i),n.notice("Video analytics configuration initialized successfully"),!0))}validateVegaFields(e){return e&&"object"==typeof e?e.applicationToken?e.endpoint?.toLowerCase()in S||(n.error("Invalid endpoint (must be us, eu, staging, gov, or jp)"),!1):(n.error("applicationToken is required"),!1):(n.error("Configuration must be an object"),!1)}validateRequiredFields(e){if(!e||"object"!=typeof e)return n.error("Configuration must be an object"),!1;const{licenseKey:t,appName:i,region:s,applicationID:r,beacon:a}=e;if(!t)return n.error("licenseKey is required"),!1;if(r){if(!a)return n.error("beacon is required when applicationID is provided"),!1;if(!Object.values(R).flatMap(e=>e).includes(a))return n.error(`Invalid beacon: ${a}`),!1}else{if(!i||!s)return n.error("appName and region are required when applicationID is not provided"),!1;if(!R[s])return n.error(`Invalid region: ${s}. Valid regions are: ${Object.keys(R).join(", ")}`),!1}return!0}validateConfigFields(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return n.error("config must be an object"),!1;const{qoeAggregate:t,obfuscate:i}=e;return void 0!==t&&"boolean"!=typeof t?(n.error("qoeAggregate must be a boolean"),!1):!(void 0!==i&&!Array.isArray(i))||(n.error("obfuscate must be an array"),!1)}filterObfuscateRules(e){return e?e.filter(e=>{const t=void 0!==e.regex&&("string"==typeof e.regex||e.regex instanceof RegExp),i=void 0!==e.replacement&&"string"==typeof e.replacement;return!(!t||!i)||(n.warn("obfuscate rule missing required 'regex' (string|RegExp) and/or 'replacement' (string), skipping:",e),!1)}):[]}sanitizeQoeIntervalFactor(e){return null==e?h.DEFAULT_QOE_INTERVAL_FACTOR:"number"==typeof e&&Number.isInteger(e)&&e>=1?e:(n.warn(`Invalid qoeIntervalFactor "${e}" — must be a positive integer. Defaulting to ${h.DEFAULT_QOE_INTERVAL_FACTOR}.`),h.DEFAULT_QOE_INTERVAL_FACTOR)}initializeGlobalConfig(e,t,i){if("Vega"===i)return void(globalThis.__NRVIDEO_CD__={info:{accountId:e.accountId,applicationToken:e.applicationToken,endpoint:e.endpoint?.toLowerCase(),...e.appName?{appName:e.appName}:{},...e.applicationID?{applicationID:e.applicationID}:{},...e.deviceInfo?{deviceInfo:e.deviceInfo}:{}},config:{qoeAggregate:t?.qoeAggregate??!0,qoeIntervalFactor:this.sanitizeQoeIntervalFactor(t?.qoeIntervalFactor),obfuscate:this.filterObfuscateRules(t?.obfuscate)}});let{licenseKey:s,appName:r,region:a,beacon:n,applicationID:o}=e;n="US"===a?h.COLLECTOR.US[0]:n||R[a],window.NRVIDEO={info:{...a?{region:a}:{},beacon:n,licenseKey:s,applicationID:o,...o?{}:{appName:r}},config:{qoeAggregate:t?.qoeAggregate??!0,qoeIntervalFactor:this.sanitizeQoeIntervalFactor(t?.qoeIntervalFactor),obfuscate:this.filterObfuscateRules(t?.obfuscate)}}}}const w=new D;class k{static addTracker(e,t){t?.info&&function(e,t,i){w.setConfiguration(e,t,i)}(t.info,t?.config,t?.src),e.on&&e.emit?(N.push(e),e.on("*",C),"function"==typeof e.trackerInit&&e.trackerInit()):n.error("Tried to load a non-tracker.",e)}static removeTracker(e){e.off("*",C),e.dispose();let t=N.indexOf(e);-1!==t&&N.splice(t,1)}static getTrackers(){return N}static send(e,t,i){return y(e,{actionName:t,...i})}static sendError(e){return y("VideoErrorAction",{actionName:"ERROR",...e})}}let N=[];function C(e){try{let t=function(e){let t={};for(let i in e)null!==e[i]&&void 0!==e[i]&&(t[i]=e[i]);return t}(e.data);n.level<=n.Levels.DEBUG?n.notice("Sent",e.type,t):n.notice("Sent",e.type),k.send(e.eventType,e.type,t)}catch(e){n.error("Error in event handler:",e.message)}}const I=k;const O=class{constructor(){this.reset(),this._createdAt=Date.now(),this._hb=!0,this._acc=0,this._bufferAcc=0}reset(){this._viewSession=null,this._viewCount=0,this._isAd=!1,this.numberOfErrors=0,this.numberOfAds=0,this.numberOfVideos=0,this.totalPlaytime=0,this.weightedAverageBitrate=0,this.totalAdPlaytime=0,this.isAdBreak=!1,this.initialBufferingHappened=!1,this.startupTime=null,this.peakBitrate=0,this.partialAverageBitrate=0,this._totalBitrateDuration=0,this.weightedBitrate=0,this._lastBitrate=null,this._lastBitrateChangeTimestamp=null,this._downloadBitrates=[],this._lastDownloadBitrate=null,this.totalSwitchUps=0,this.totalSwitchDowns=0,this.totalPauseTime=0,this._playedRenditions=new Set,this.hadStartupError=!1,this.hadPlaybackError=!1,this.totalRebufferingTime=0,this.resetFlags(),this.resetChronos()}resetFlags(){this.isPlayerReady=!1,this.isRequested=!1,this.isStarted=!1,this.isPaused=!1,this.isSeeking=!1,this.isBuffering=!1,this.isPlaying=!1}resetChronos(){this.timeSinceRequested=new u,this.timeSinceStarted=new u,this.timeSincePaused=new u,this.timeSinceSeekBegin=new u,this.timeSinceBufferBegin=new u,this.timeSinceAdBreakStart=new u,this.timeSinceLastDownload=new u,this.timeSinceLastHeartbeat=new u,this.timeSinceLastRenditionChange=new u,this.timeSinceLastAdQuartile=new u,this.timeSinceLastAd=new u,this.timeSinceLastError=new u,this.timeSinceLastAdError=new u,this.timeSinceResumed=new u,this.timeSinceSeekEnd=new u,this.playtimeSinceLastEvent=new u,this.customTimeSinceAttributes={},this.elapsedTime=new u,this.bufferElapsedTime=new u,this._totalAdPlaytime=new u}isAd(){return this._isAd}setIsAd(e){this._isAd=e}setTimeSinceAttribute(e){this.customTimeSinceAttributes[e]=new u,this.customTimeSinceAttributes[e].start()}removeTimeSinceAttribute(e){delete this.customTimeSinceAttributes[e]}getViewSession(){if(!this._viewSession){let e=(new Date).getTime(),t=Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2);this._viewSession=e+"-"+t}return this._viewSession}getViewId(){return this.getViewSession()+"-"+this._viewCount}getStateAttributes(e){e=e||{},this.isAd()?(this.isRequested&&(e.timeSinceAdRequested=this.timeSinceRequested.getDeltaTime(),e.timeSinceLastAdHeartbeat=this.timeSinceLastHeartbeat.getDeltaTime()),this.isStarted&&(e.timeSinceAdStarted=this.timeSinceStarted.getDeltaTime()),this.isPaused&&(e.timeSinceAdPaused=this.timeSincePaused.getDeltaTime()),this.isBuffering&&(e.timeSinceAdBufferBegin=this.timeSinceBufferBegin.getDeltaTime()),this.isSeeking&&(e.timeSinceAdSeekBegin=this.timeSinceSeekBegin.getDeltaTime()),this.isAdBreak&&(e.timeSinceAdBreakBegin=this.timeSinceAdBreakStart.getDeltaTime()),this.numberOfErrors>0&&this.timeSinceLastAdError.startTime>0&&(e.timeSinceLastAdError=this.timeSinceLastAdError.getDeltaTime()),e.numberOfAds=this.numberOfAds):(this.isRequested&&(e.timeSinceRequested=this.timeSinceRequested.getDeltaTime(),e.timeSinceLastHeartbeat=this.timeSinceLastHeartbeat.getDeltaTime()),this.isStarted&&(e.timeSinceStarted=this.timeSinceStarted.getDeltaTime()),this.isPaused&&(e.timeSincePaused=this.timeSincePaused.getDeltaTime()),this.isBuffering&&(e.timeSinceBufferBegin=this.timeSinceBufferBegin.getDeltaTime()),this.isSeeking&&(e.timeSinceSeekBegin=this.timeSinceSeekBegin.getDeltaTime()),e.timeSinceLastAd=this.timeSinceLastAd.getDeltaTime(),this.numberOfErrors>0&&this.timeSinceLastError.startTime>0&&(e.timeSinceLastError=this.timeSinceLastError.getDeltaTime()),e.numberOfVideos=this.numberOfVideos),e.numberOfErrors=this.numberOfErrors,this.isAd()||(this.playtimeSinceLastEvent.startTime>0?e.playtimeSinceLastEvent=this.playtimeSinceLastEvent.getDeltaTime():e.playtimeSinceLastEvent=0,this.isPlaying?this.playtimeSinceLastEvent.start():this.playtimeSinceLastEvent.reset(),this.totalPlaytime+=e.playtimeSinceLastEvent,e.totalPlaytime=this.totalPlaytime);for(const[t,i]of Object.entries(this.customTimeSinceAttributes))e[t]=i.getDeltaTime();return e}getQoeAttributes(e){e=e||{};const t={};try{if(null!==this.startupTime&&(t.startupTime=this.startupTime),this.peakBitrate>0&&(t.peakBitrate=this.peakBitrate),t.hadStartupError=this.hadStartupError,t.hadPlaybackError=this.hadPlaybackError,t.totalRebufferingTime=this.totalRebufferingTime,t.rebufferingRatio=this.totalPlaytime>0?this.totalRebufferingTime/this.totalPlaytime*100:0,t.totalPlaytime=this.totalPlaytime,t.averageBitrate=this.weightedBitrate,t.numberOfErrors=this.numberOfErrors,this._downloadBitrates.length>0){const e=this._downloadBitrates.reduce((e,t)=>e+t,0);t.avgDownloadRate=Math.round(e/this._downloadBitrates.length),t.minDownloadRate=Math.min(...this._downloadBitrates),t.maxDownloadRate=Math.max(...this._downloadBitrates)}t.totalSwitchUps=this.totalSwitchUps,t.totalSwitchDowns=this.totalSwitchDowns,t.totalPauseTime=this.timeSincePaused.getDuration(),t.totalViewSessionTime=this.totalPlaytime,t.totalRenditions=this._playedRenditions.size,t.qoeAggregateVersion="1.1.0"}catch(e){n.error("Failed to add attributes for QOE KPIs",e.message)}return e.qoe=t,e}calculateBufferType(e){let t="";return t=e?"initial":this.isSeeking?"seek":this.isPaused?"pause":"connection",n.debug("Buffer Type = "+t),t}goViewCountUp(){this._viewCount++}goPlayerReady(){return!this.isPlayerReady&&(this.isPlayerReady=!0,!0)}goRequest(){return!this.isRequested&&(this.isRequested=!0,this.timeSinceLastAd.reset(),this.timeSinceRequested.start(),!0)}goStart(){return!(!this.isRequested||this.isStarted)&&(this.isAd()?this.numberOfAds++:this.numberOfVideos++,this.isStarted=!0,this.isPlaying=!0,this.timeSinceStarted.start(),this.playtimeSinceLastEvent.start(),!0)}goEnd(){return!!this.isRequested&&(this.numberOfErrors=0,this.resetFlags(),this.timeSinceRequested.stop(),this.timeSinceStarted.stop(),this.playtimeSinceLastEvent.stop(),this.isPlaying=!1,!0)}goPause(){return!(!this.isStarted||this.isPaused)&&(this.isPaused=!0,this.isPlaying=!1,this.timeSincePaused.start(),this.playtimeSinceLastEvent.stop(),this.timeSinceResumed.reset(),this.isBuffering&&(this._bufferAcc+=this.bufferElapsedTime.getDeltaTime()),this.elapsedTime.start(),!0)}goResume(){return!(!this.isStarted||!this.isPaused)&&(this.isPaused=!1,this.isPlaying=!0,this.timeSincePaused.stop(),this.timeSinceResumed.start(),this._hb?(this._acc=this.elapsedTime.getDeltaTime(),this._hb=!1):(this.isBuffering&&this.bufferElapsedTime.start(),this._acc+=this.elapsedTime.getDeltaTime()),!0)}goBufferStart(){return!(!this.isRequested||this.isBuffering)&&(this.isBuffering=!0,this.isPlaying=!1,this.timeSinceBufferBegin.start(),this.bufferElapsedTime.start(),!0)}goBufferEnd(){return!(!this.isRequested||!this.isBuffering)&&(this.isBuffering=!1,this.isPlaying=!0,this.timeSinceBufferBegin.stop(),this._hb?(this._bufferAcc=this.bufferElapsedTime.getDeltaTime(),this._hb=!1):this._bufferAcc+=this.bufferElapsedTime.getDeltaTime(),!this.isAd()&&this.initialBufferingHappened&&(this.totalRebufferingTime+=this.timeSinceBufferBegin.stopTime-this.timeSinceBufferBegin.startTime),!0)}goSeekStart(){return!(!this.isStarted||this.isSeeking)&&(this.isSeeking=!0,this.isPlaying=!1,this.timeSinceSeekBegin.start(),this.timeSinceSeekEnd.reset(),!0)}goSeekEnd(){return!(!this.isStarted||!this.isSeeking)&&(this.isSeeking=!1,this.isPlaying=!0,this.timeSinceSeekBegin.stop(),this.timeSinceSeekEnd.start(),!0)}goAdBreakStart(){return!this.isAdBreak&&(this.isAdBreak=!0,this.timeSinceAdBreakStart.start(),!0)}goAdBreakEnd(){return!!this.isAdBreak&&(this.isRequested=!1,this.isAdBreak=!1,this.totalAdPlaytime=this.timeSinceAdBreakStart.getDeltaTime(),this.timeSinceAdBreakStart.stop(),!0)}goDownload(){this.timeSinceLastDownload.start()}goHeartbeat(){this.timeSinceLastHeartbeat.start()}goRenditionChange(){this.timeSinceLastRenditionChange.start()}goAdQuartile(){this.timeSinceLastAdQuartile.start()}goError(){this.isError=!0,this.numberOfErrors++,this.isAd()?this.timeSinceLastAdError.start():(this.timeSinceLastError.start(),this.isStarted?this.hadPlaybackError=!0:this.hadStartupError=!0)}goLastAd(){this.timeSinceLastAd.start()}trackContentBitrateState(e){if(e&&"number"==typeof e){this.peakBitrate=Math.max(this.peakBitrate,e);const t=Date.now();if(!this.isPlaying){if(null!==this._lastBitrate&&null!==this._lastBitrateChangeTimestamp){const e=t-this._lastBitrateChangeTimestamp;e>0&&(this.partialAverageBitrate+=this._lastBitrate*e,this._totalBitrateDuration+=e),this._lastBitrateChangeTimestamp=null}return void(this._lastBitrate=e)}if(null===this._lastBitrateChangeTimestamp&&null!==this._lastBitrate&&(this._lastBitrateChangeTimestamp=t),null!==this._lastBitrate&&this._lastBitrate!==e&&null!==this._lastBitrateChangeTimestamp){const e=t-this._lastBitrateChangeTimestamp;e>0&&(this.partialAverageBitrate+=this._lastBitrate*e,this._totalBitrateDuration+=e),this._lastBitrateChangeTimestamp=t}null===this._lastBitrateChangeTimestamp&&(this._lastBitrateChangeTimestamp=t),this._lastBitrate=e;let i=this.partialAverageBitrate,s=this._totalBitrateDuration;const r=t-this._lastBitrateChangeTimestamp;r>0&&(i+=e*r,s+=r),this.weightedBitrate=s>0?Math.round(i/s):e}}trackDownloadRate(e){!e||"number"!=typeof e||e<=0||e!==this._lastDownloadBitrate&&(this._downloadBitrates.push(e),this._lastDownloadBitrate=e)}addPlayedRendition(e,t){e&&t&&this._playedRenditions.add(`${e}x${t}`)}resetViewIdTrackedState(){this.peakBitrate=0,this.startupTime=null,this.partialAverageBitrate=0,this._totalBitrateDuration=0,this.weightedBitrate=0,this._lastBitrate=null,this._lastBitrateChangeTimestamp=null,this._downloadBitrates=[],this._lastDownloadBitrate=null,this.totalSwitchUps=0,this.totalSwitchDowns=0,this.timeSincePaused.reset(),this._playedRenditions=new Set}clearTotalAdsTime(){n.debug("clear total ads time",this.totalAdTime),this._totalAdPlaytime.reset()}totalAdTime(){return this._totalAdPlaytime.getDuration()}startAdsTime(){return n.debug("startAdsTime"),this._totalAdPlaytime.start()}stopAdsTime(){return n.debug("stopAdsTime"),this._totalAdPlaytime.stop()}setStartupTime(e){null===this.startupTime&&(this.startupTime=Math.max(this.timeSinceRequested.getDeltaTime()-e,0))}};class P extends g{constructor(e,t){super(),this.state=new O,this.adsTracker=null,this._lastBufferType=null,this._userId=null,this._src=null,t=t||{},this.setOptions(t),e&&this.setPlayer(e,t.tag),n.notice("Tracker "+this.getTrackerName()+" v"+this.getTrackerVersion()+" is ready.")}setUserId(e){this._userId=e}setOptions(e){e&&(e.adsTracker&&this.setAdsTracker(e.adsTracker),"boolean"==typeof e.isAd&&this.setIsAd(e.isAd),void 0!==e.src&&(null!==this._src&&this._src!==e.src?n.warn(`setOptions: src is locked to '${this._src}'. Ignoring override '${e.src}'.`):(this._src=e.src,this.adsTracker&&null==this.adsTracker._src&&(this.adsTracker._src=this._src))),g.prototype.setOptions.apply(this,arguments))}setPlayer(e,t){(this.player||this.tag)&&this.dispose(),"undefined"!=typeof document&&document.getElementById&&("string"==typeof e&&(e=document.getElementById(e)),"string"==typeof t&&(t=document.getElementById(t))),t=t||e,this.player=e,this.tag=t,this.registerListeners()}isAd(){return this.state.isAd()}setIsAd(e){this.state.setIsAd(e)}setAdsTracker(e){this.disposeAdsTracker(),e&&(this.adsTracker=e,this.adsTracker.setIsAd(!0),this.adsTracker.parentTracker=this,null!=this._src&&null==e._src&&(e._src=this._src),this.adsTracker.on("*",V.bind(this)))}disposeAdsTracker(){this.adsTracker&&(this.adsTracker.off("*",V),this.adsTracker.dispose())}dispose(){this.stopHeartbeat(),this.disposeAdsTracker(),this.unregisterListeners(),this.player=null,this.tag=null}registerListeners(){}unregisterListeners(){}getViewId(){return this.parentTracker?this.parentTracker.getViewId():this.state.getViewId()}getViewSession(){return this.parentTracker?this.parentTracker.getViewSession():this.state.getViewSession()}getVideoId(){return null}getTitle(){return null}isLive(){return null}getBitrate(){return null}getManifestBitrate(){return null}getSegmentDownloadBitrate(){return null}getNetworkDownloadBitrate(){return null}getWebkitBitrate(){if(this.tag&&this.tag.webkitVideoDecodedByteCount){let e;if(this._lastWebkitBitrate){e=this.tag.webkitVideoDecodedByteCount;let t=e-this._lastWebkitBitrate,i=this.getHeartbeat()/1e3;e=Math.round(t/i*8)}return this._lastWebkitBitrate=this.tag.webkitVideoDecodedByteCount,e||null}}getRenditionName(){return null}getRenditionBitrate(){return null}getRenditionShift(e){let t,i=this.getManifestBitrate();return this.isAd()?(t=this._lastAdRendition,e&&(this._lastAdRendition=i)):(t=this._lastRendition,e&&(this._lastRendition=i)),i&&t?i>t?"up":i<t?"down":null:null}getRenditionHeight(){return this.tag?this.tag.videoHeight:null}getRenditionWidth(){return this.tag?this.tag.videoWidth:null}getDuration(){return this.tag?this.tag.duration:null}getPlayhead(){return this.tag?this.tag.currentTime:null}getLanguage(){return null}getSrc(){return this.tag?this.tag.currentSrc:null}getPlayrate(){return this.tag?this.tag.playbackRate:null}isMuted(){return this.tag?this.tag.muted:null}isFullscreen(){return null}getCdn(){return null}getPlayerName(){return this.getTrackerName()}getPlayerVersion(){return l}getFps(){return null}isAutoplayed(){return this.tag?this.tag.autoplay:null}getPreload(){return this.tag?this.tag.preload:null}getAdQuartile(){return null}getAdPosition(){return this.parentTracker?this.parentTracker.state.isStarted?"mid":"pre":null}getAdPartner(){return null}getAdCreativeId(){return null}getInstrumentationProvider(){return null}getInstrumentationName(){return null}getInstrumentationVersion(){return null}getAttributes(e,t){if(void 0===(e=g.prototype.getAttributes.apply(this,arguments)).isAd&&(e.isAd=this.isAd()),e.viewSession=this.getViewSession(),e.viewId=this.getViewId(),e.playerName=this.getPlayerName(),e.playerVersion=this.getPlayerVersion(),e["instrumentation.provider"]=this.getInstrumentationProvider(),e["instrumentation.name"]=this.getInstrumentationName(),e["instrumentation.version"]=this.getInstrumentationVersion(),e["enduser.id"]=this._userId,e.src=this._src||"Browser","customAction"===t)return e;try{e.pageUrl=window.location.href}catch(e){}this.isAd()?(e.adId=this.getVideoId(),e.adTitle=this.getTitle(),e.adSrc=this.getSrc(),e.adCdn=this.getCdn(),this.state.isStarted&&(e.adBitrate=this.getBitrate()||0),e.adRenditionName=this.getRenditionName(),e.adRenditionHeight=this.getRenditionHeight(),e.adRenditionWidth=this.getRenditionWidth(),e.adDuration=this.getDuration(),e.adPlayhead=this.getPlayhead(),e.adLanguage=this.getLanguage(),e.adIsMuted=this.isMuted(),e.adFps=this.getFps(),e.adPosition=this.getAdPosition(),e.adCreativeId=this.getAdCreativeId(),e.adPartner=this.getAdPartner()):(e.contentId=this.getVideoId(),e.contentTitle=this.getTitle(),e.contentSrc=this.getSrc(),e.contentCdn=this.getCdn(),e.contentPlayhead=this.getPlayhead(),e.contentIsLive=this.isLive(),this.state.isStarted&&(e.contentBitrate=this.getBitrate()||0,e.contentManifestBitrate=this.getManifestBitrate()||0,e.contentSegmentDownloadBitrate=this.getSegmentDownloadBitrate()||0,e.contentNetworkDownloadBitrate=this.getNetworkDownloadBitrate()||0),e.contentRenditionName=this.getRenditionName(),e.contentRenditionHeight=this.getRenditionHeight(),e.contentRenditionWidth=this.getRenditionWidth(),e.contentDuration=this.getDuration(),e.contentLanguage=this.getLanguage(),e.contentPlayrate=this.getPlayrate(),e.contentIsFullscreen=this.isFullscreen(),e.contentIsMuted=this.isMuted(),e.contentIsAutoplayed=this.isAutoplayed(),e.contentPreload=this.getPreload(),e.contentFps=this.getFps(),null!=this.adsTracker&&this.adsTracker.state.totalAdPlaytime>0&&(e.totalAdPlaytime=this.adsTracker.state.totalAdPlaytime)),this.state.getStateAttributes(e),this.state.isStarted&&!this.isAd()&&(this.state.trackContentBitrateState(e.contentBitrate),this.state.trackDownloadRate(e.contentNetworkDownloadBitrate),this.state.addPlayedRendition(e.contentRenditionHeight,e.contentRenditionWidth));for(let t in this.customData)e[t]=this.customData[t];if(!this.isAd()){this.state.getQoeAttributes(e);const t=e.qoe;for(let e in this.customData)t[e]=this.customData[e]}return e}sendCustom(e,t,i){i=i||{},this.sendVideoCustomAction(e,i),this.state.setTimeSinceAttribute(t)}sendPlayerReady(e){this.state.goPlayerReady()&&(e=e||{},this.sendVideoAction(P.Events.PLAYER_READY,e))}sendRequest(e){if(this.state.goRequest()){let t;this.isAd()?(t=P.Events.AD_REQUEST,this.sendVideoAdAction(t,e)):(t=P.Events.CONTENT_REQUEST,this.sendVideoAction(t,e))}}sendStart(e){if(this.state.goStart()){let t;if(this.isAd())t=P.Events.AD_START,this.parentTracker&&(this.parentTracker.state.isPlaying=!1),this.sendVideoAdAction(t,e),this.state.startAdsTime();else{t=P.Events.CONTENT_START;let i=0;this.adsTracker&&((this.adsTracker.state.isPlaying||this.adsTracker.state.isBuffering)&&(this.adsTracker.state.stopAdsTime(),this.adsTracker.state.isPlaying=!1,this.adsTracker.state.isBuffering=!1),i=this.adsTracker.state.totalAdTime()??0),this.state.setStartupTime(i),this.sendVideoAction(t,e);const s=this.getHarvester?.();s?.setBeforeDrainCallback(()=>{if(this.state){const e=this.state.getQoeAttributes({}).qoe;s.refreshQoeKpis(e,this.getViewId())}})}this.startHeartbeat(),this.state.goHeartbeat()}}sendEnd(e){if(this.state.goEnd()){let t;if(e=e||{},this.isAd()?(t=P.Events.AD_END,e.timeSinceAdRequested=this.state.timeSinceRequested.getDeltaTime(),e.timeSinceAdStarted=this.state.timeSinceStarted.getDeltaTime(),this.parentTracker&&(this.parentTracker.state.isPlaying=!0,this.parentTracker.state.timeSincePaused.reset()),this.state.stopAdsTime()):(t=P.Events.CONTENT_END,e.timeSinceRequested=this.state.timeSinceRequested.getDeltaTime(),e.timeSinceStarted=this.state.timeSinceStarted.getDeltaTime()),this.stopHeartbeat(),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e),this.parentTracker&&this.isAd()&&this.parentTracker.state.goLastAd(),this.state.goViewCountUp(),this.state.totalPlaytime=0,!this.isAd()){const e=this.getHarvester?.();e?.forceNextQoeCycle?.(),e?.setBeforeDrainCallback?.(null),this.adsTracker&&this.adsTracker.state.clearTotalAdsTime(),this.state.resetViewIdTrackedState()}}}sendPause(e){if(this.state.goPause()){let t=this.isAd()?P.Events.AD_PAUSE:P.Events.CONTENT_PAUSE;this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendResume(e){if(this.state.goResume()){let t;e=e||{},this.isAd()?(t=P.Events.AD_RESUME,e.timeSinceAdPaused=this.state.timeSincePaused.getDeltaTime()):(t=P.Events.CONTENT_RESUME,e.timeSincePaused=this.state.timeSincePaused.getDeltaTime()),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendBufferStart(e){if(this.state.goBufferStart()){let t;e=e||{},t=this.isAd()?P.Events.AD_BUFFER_START:P.Events.CONTENT_BUFFER_START,e=this.buildBufferAttributes(e),this._lastBufferType=e.bufferType,this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendBufferEnd(e){if(this.state.goBufferEnd()){let t;e=e||{},this.isAd()?(t=P.Events.AD_BUFFER_END,e.timeSinceAdBufferBegin=this.state.timeSinceBufferBegin.getDeltaTime()):(t=P.Events.CONTENT_BUFFER_END,e.timeSinceBufferBegin=this.state.timeSinceBufferBegin.getDeltaTime()),e=this.buildBufferAttributes(e),null!=this._lastBufferType&&(e.bufferType=this._lastBufferType),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e),this.state.initialBufferingHappened=!0}}buildBufferAttributes(e){return null==e.timeSinceStarted||e.timeSinceStarted<100?e.isInitialBuffering=!this.state.initialBufferingHappened:e.isInitialBuffering=!1,e.bufferType=this.state.calculateBufferType(e.isInitialBuffering),e.timeSinceResumed=this.state.timeSinceResumed.getDeltaTime(),e.timeSinceSeekEnd=this.state.timeSinceSeekEnd.getDeltaTime(),e}sendSeekStart(e){if(this.state.goSeekStart()){let t;t=this.isAd()?P.Events.AD_SEEK_START:P.Events.CONTENT_SEEK_START,this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendSeekEnd(e){if(this.state.goSeekEnd()){let t;e=e||{},this.isAd()?(t=P.Events.AD_SEEK_END,e.timeSinceAdSeekBegin=this.state.timeSinceSeekBegin.getDeltaTime()):(t=P.Events.CONTENT_SEEK_END,e.timeSinceSeekBegin=this.state.timeSinceSeekBegin.getDeltaTime()),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendDownload(e){(e=e||{}).state||n.warn("Called sendDownload without { state: xxxxx }."),this.sendVideoAction(P.Events.DOWNLOAD,e),this.state.goDownload()}sendError(e){(e=e||{}).isAd=this.isAd(),this.state.goError();let t=this.isAd()?P.Events.AD_ERROR:P.Events.CONTENT_ERROR;this.sendVideoErrorAction(t,e)}sendRenditionChanged(e){(e=e||{}).timeSinceLastRenditionChange=this.state.timeSinceLastRenditionChange.getDeltaTime();const{oldBitrate:t,newBitrate:i}=e;let s;this.isAd()||void 0===t||void 0===i||(i>t?(e.shift="up",this.state.totalSwitchUps+=1):i<t?(e.shift="down",this.state.totalSwitchDowns+=1):e.shift=null),delete e.oldBitrate,delete e.newBitrate,s=this.isAd()?P.Events.AD_RENDITION_CHANGE:P.Events.CONTENT_RENDITION_CHANGE,this.isAd()?this.sendVideoAdAction(s,e):this.sendVideoAction(s,e),this.state.goRenditionChange()}sendHeartbeat(e){if(this.state.isRequested){let t,i=this.getHeartbeat();this.state._hb=!0,i=this.adjustElapsedTimeForPause(i),this.isAd()?(t=P.Events.AD_HEARTBEAT,"bitmovin-ads"===this.getPlayerName()?this.sendVideoAdAction(t,e):this.sendVideoAdAction(t,{elapsedTime:i,...e})):(t=P.Events.CONTENT_HEARTBEAT,this.sendVideoAction(t,{elapsedTime:i,...e})),this.state.goHeartbeat()}}adjustElapsedTimeForPause(e){return this.state._acc&&(e-=this.state._acc,this.state._acc=0),this.state.isPaused&&((e-=this.state.elapsedTime.getDeltaTime())<10&&(e=0),this.state.elapsedTime.start()),this.state._bufferAcc?(e-=this.state._bufferAcc,this.state._bufferAcc=0):this.state.isBuffering&&((e-=this.state.bufferElapsedTime.getDeltaTime())<5&&(e=0),this.state.bufferElapsedTime.start()),Math.max(0,e)}sendAdBreakStart(e){this.isAd()&&this.state.goAdBreakStart()&&(this.state.totalAdPlaytime=0,this.parentTracker&&(this.parentTracker.state.isPlaying=!1),this.sendVideoAdAction(P.Events.AD_BREAK_START,e))}sendAdBreakEnd(e){this.isAd()&&this.state.goAdBreakEnd()&&((e=e||{}).timeSinceAdBreakBegin=this.state.timeSinceAdBreakStart.getDeltaTime(),this.sendVideoAdAction(P.Events.AD_BREAK_END,e),this.parentTracker&&(this.parentTracker.state.isPlaying=!0),this.stopHeartbeat(),this.parentTracker&&this.isAd()&&this.parentTracker.state.goLastAd())}sendAdQuartile(e){this.isAd()&&((e=e||{}).quartile||n.warn("Called sendAdQuartile without { quartile: xxxxx }."),e.timeSinceLastAdQuartile=this.state.timeSinceLastAdQuartile.getDeltaTime(),this.sendVideoAdAction(P.Events.AD_QUARTILE,e),this.state.goAdQuartile())}sendAdClick(e){this.isAd()&&((e=e||{}).url||n.warn("Called sendAdClick without { url: xxxxx }."),this.sendVideoAdAction(P.Events.AD_CLICK,e))}}function V(e){e.type!==P.Events.AD_ERROR?this.sendVideoAdAction(e.type,e.data):this.sendVideoErrorAction(e.type,e.data)}P.Events={PLAYER_READY:"PLAYER_READY",DOWNLOAD:"DOWNLOAD",ERROR:"ERROR",CONTENT_REQUEST:"CONTENT_REQUEST",CONTENT_START:"CONTENT_START",CONTENT_END:"CONTENT_END",CONTENT_PAUSE:"CONTENT_PAUSE",CONTENT_RESUME:"CONTENT_RESUME",CONTENT_SEEK_START:"CONTENT_SEEK_START",CONTENT_SEEK_END:"CONTENT_SEEK_END",CONTENT_BUFFER_START:"CONTENT_BUFFER_START",CONTENT_BUFFER_END:"CONTENT_BUFFER_END",CONTENT_HEARTBEAT:"CONTENT_HEARTBEAT",CONTENT_RENDITION_CHANGE:"CONTENT_RENDITION_CHANGE",CONTENT_ERROR:"CONTENT_ERROR",AD_REQUEST:"AD_REQUEST",AD_START:"AD_START",AD_END:"AD_END",AD_PAUSE:"AD_PAUSE",AD_RESUME:"AD_RESUME",AD_SEEK_START:"AD_SEEK_START",AD_SEEK_END:"AD_SEEK_END",AD_BUFFER_START:"AD_BUFFER_START",AD_BUFFER_END:"AD_BUFFER_END",AD_HEARTBEAT:"AD_HEARTBEAT",AD_RENDITION_CHANGE:"AD_RENDITION_CHANGE",AD_ERROR:"AD_ERROR",AD_BREAK_START:"AD_BREAK_START",AD_BREAK_END:"AD_BREAK_END",AD_QUARTILE:"AD_QUARTILE",AD_CLICK:"AD_CLICK"};const H=P,{MAX_PAYLOAD_SIZE:L,MAX_EVENTS_PER_BATCH:Q}=h;class x{constructor(){this.buffer=[],this.maxPayloadSize=L,this.maxEventsPerBatch=Q,this.currentPayloadSize=0,this.totalEvents=0,this.smartHarvestPayloadThreshold=Math.floor(.6*this.maxPayloadSize),this.overflowPayloadThreshold=Math.floor(.9*this.maxPayloadSize),this.smartHarvestEventThreshold=Math.floor(.6*this.maxEventsPerBatch),this.overflowEventThreshold=Math.floor(.9*this.maxEventsPerBatch),this.onSmartHarvestTrigger=null}addOrReplaceByActionName(e,t){const i=this.buffer.findIndex(t=>t.actionName===e);try{return-1===i?this.add(t):this.add(t,i),!0}catch(e){return n.error("Failed to set or replace the event to buffer:",e.message),!1}}addOrReplaceByActionNameAndViewId(e,t,i){const s=this.buffer.findIndex(i=>i.actionName===e&&i.viewId===t);try{return-1===s?this.add(i):this.add(i,s),!0}catch(e){return n.error("Failed to set or replace the event to buffer:",e.message),!1}}findByActionNameAndViewId(e,t){return this.buffer.find(i=>i.actionName===e&&i.viewId===t)||null}findByActionName(e){return this.buffer.find(t=>t.actionName===e)||null}add(e,t){try{const i=v(e),s=this.currentPayloadSize+i>=this.maxPayloadSize,r=this.totalEvents+1>=this.maxEventsPerBatch;if((s||r)&&this.makeRoom(i),null!=t&&t>-1){const s=v(this.buffer[t]);this.buffer[t]=e,this.currentPayloadSize+=i-s}else this.buffer.push(e),this.totalEvents++,this.currentPayloadSize+=i;return this.checkSmartHarvestTrigger(),!0}catch(e){return n.error("Failed to add event to buffer:",e.message),!1}}checkSmartHarvestTrigger(){const e=this.currentPayloadSize/this.maxPayloadSize,t=this.totalEvents/this.maxEventsPerBatch,i=this.currentPayloadSize>=this.overflowPayloadThreshold,s=this.totalEvents>=this.overflowEventThreshold;if(i||s){const s=i?`payload ${this.currentPayloadSize}/${this.maxPayloadSize} bytes (${Math.round(100*e)}%)`:`events ${this.totalEvents}/${this.maxEventsPerBatch} (${Math.round(100*t)}%)`;n.warn(`OVERFLOW PREVENTION: ${s} - Emergency harvest triggered`),this.onSmartHarvestTrigger&&"function"==typeof this.onSmartHarvestTrigger&&this.onSmartHarvestTrigger("overflow",90)}else{const e=this.currentPayloadSize>=this.smartHarvestPayloadThreshold,t=this.totalEvents>=this.smartHarvestEventThreshold;(e||t)&&this.onSmartHarvestTrigger&&"function"==typeof this.onSmartHarvestTrigger&&this.onSmartHarvestTrigger("smart",60)}}setSmartHarvestCallback(e){this.onSmartHarvestTrigger=e}drain(){try{const e=this.buffer.splice(0);return this.totalEvents=0,this.currentPayloadSize=0,e}catch(e){return n.error("Failed to drain events from buffer:",e.message),[]}}isEmpty(){return 0===this.totalEvents}size(){return this.totalEvents}clear(){this.buffer=[],this.totalEvents=0}makeRoom(e){if(e>this.maxPayloadSize)n.error("Event dropped: Event size exceeds maximum payload size.");else for(;(this.totalEvents>=this.maxEventsPerBatch||this.currentPayloadSize+e>=this.maxPayloadSize)&&this.buffer.length>0;){const e=v(this.buffer.shift());this.totalEvents--,this.currentPayloadSize-=e,n.warn("Event buffer full, oldest event removed.")}}}const{MAX_PAYLOAD_SIZE:F,MAX_EVENTS_PER_BATCH:q}=h;class z{constructor(){this.retryQueue=[],this.maxQueueSize=q,this.maxQueueSizeBytes=F}addFailedEvents(e){try{const t=Array.isArray(e)?e:[e];n.notice(`Adding ${t.length} failed events to retry queue`,{queueSizeBefore:this.retryQueue.length});for(const e of t){this.retryQueue.length>=this.maxQueueSize&&this.evictOldestEvent();const t=v(e);for(;v(this.retryQueue)+t>this.maxQueueSizeBytes;)this.evictOldestEvent();this.retryQueue.push({...e})}}catch(e){n.error("Failed to add events to retry queue:",e.message)}}discardEvent(e,t){n.warn("Discarded event",{reason:t,eventType:e.eventType})}evictOldestEvent(){if(this.retryQueue.length>0){const e=this.retryQueue.shift();this.discardEvent(e,"Queue full - evicted oldest")}}getRetryEventsToFit(e,t){const i=[];let s=0,r=0;for(let a=this.retryQueue.length-1;a>=0;a--){const n=this.retryQueue[a];if(r>=t)break;const o=v(n);if(s+o>e)break;i.unshift(n),s+=o,r++,this.retryQueue.splice(a,1)}return i}getQueueSize(){return this.retryQueue.length}clear(){this.retryQueue=[]}}function U(e,t){return t&&0!==t.length?t.reduce((e,t)=>{let i;try{if(t.regex instanceof RegExp){const e=t.regex.flags.includes("g")?t.regex.flags:t.regex.flags+"g";i=new RegExp(t.regex.source,e)}else i=new RegExp(t.regex,"g")}catch(i){return n.warn("applyObfuscationRules: invalid regex, skipping rule:",t.regex,i.message),e}return e.replace(i,t.replacement)},e):e}class M{async send(e,t){const{url:i,payload:s,options:r={}}=e;try{if(!i||!s)throw new Error("URL and payload are required");const e={url:i,payload:s,options:r,callback:t};await this.executeRequest(e)}catch(e){n.error("Failed to send request:",e.message),t({retry:!1,status:0,error:e.message})}}async executeRequest(e){const{url:t,payload:i,options:s,callback:r}=e,a=Date.now();try{const r=U(JSON.stringify(i.body),window.NRVIDEO?.config?.obfuscate);if(s.isFinalHarvest&&navigator.sendBeacon){const i=await this.sendWithBeacon(t,r),s={success:i,status:i?204:0};return void this.handleRequestComplete(e,s,a)}const n=await this.fetchWithTimeout(t,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:s.isFinalHarvest},1e4),o={success:n.ok,status:n.status,statusText:n.statusText};this.handleRequestComplete(e,o,a)}catch(t){const i={success:!1,status:0,error:t.message};this.handleRequestComplete(e,i,a)}}handleRequestComplete(e,t){const{callback:i}=e;i({retry:!t.success&&(0===t.status||function(e){switch(e){case 408:case 429:case 500:return!0;case 401:case 403:case 404:return!1}return e>=502&&e<=504||e>=512&&e<=530}(t.status)),status:t.status,error:t.error})}async sendWithBeacon(e,t){try{return navigator.sendBeacon(e,t)}catch(e){return n.warn("sendBeacon failed, falling back to fetch:",e.message),!1}}async fetchWithTimeout(e,t,i){const s=new AbortController,r=setTimeout(()=>s.abort(),i);try{const i=await fetch(e,{...t,signal:s.signal});return clearTimeout(r),i}catch(e){if(clearTimeout(r),"AbortError"===e.name)throw new Error(`Request timeout after ${i}ms`);throw e}}}function G(e,t){return!!t&&(t.actionName===g.Events.QOE_AGGREGATE?t.viewId?e.addOrReplaceByActionNameAndViewId(g.Events.QOE_AGGREGATE,t.viewId,t):e.addOrReplaceByActionName(g.Events.QOE_AGGREGATE,t):e.add(t))}function K(e,t,i){if(!e||!t)return;const s=i?e.findByActionNameAndViewId(g.Events.QOE_AGGREGATE,i):e.findByActionName(g.Events.QOE_AGGREGATE);if(!s)return;const r={...s};for(const e of h.QOE_KPI_KEYS)e in t&&(r[e]=t[e]);i?e.addOrReplaceByActionNameAndViewId(g.Events.QOE_AGGREGATE,i,r):e.addOrReplaceByActionName(g.Events.QOE_AGGREGATE,r)}function $(e,t){const i=e[t.viewId];if(!i)return!1;for(const e of h.QOE_KPI_KEYS)if(t[e]!==i[e])return!1;return!0}function j(e,t){const i={};for(const e of h.QOE_KPI_KEYS)i[e]=t[e];e[t.viewId]=i}function W(e,t,i){if(t)return e;const s=[];for(const t of e)t.actionName===g.Events.QOE_AGGREGATE?i.add(t):s.push(t);return s}function Y(e,t,i){for(let s=e.length-1;s>=0;s--){const r=e[s];r.actionName===g.Events.QOE_AGGREGATE&&(!i&&$(t,r)?e.splice(s,1):j(t,r))}}function X({interval:e,onTick:t,errorLabel:i}){let s=!1,r=null,a=e;function o(){s&&(r=setTimeout(async()=>{r=null;try{await t()}catch(e){n.error(`${i}: scheduled tick failed:`,e.message)}finally{s&&o()}},a))}return{start(){s||(s=!0,o())},stop(){s=!1,r&&(clearTimeout(r),r=null)},cancelAndReschedule(){r&&(clearTimeout(r),r=null),s&&o()},updateInterval(e){"number"!=typeof e||e<=0||(a=e,s&&r&&(clearTimeout(r),r=null,o()))},isRunning:()=>s}}class Z{constructor(e){this.eventBuffer=e,this.retryQueueHandler=new z,this.httpClient=new M,this.fallBackUrl="",this.retryCount=0,this.eventBuffer instanceof x&&this.eventBuffer.setSmartHarvestCallback((e,t)=>this.triggerSmartHarvest(e,t)),this.harvestCycle=h.INTERVAL,this.isHarvesting=!1,this.qoeCycleCount=1,this.forceNextQoeCycle=!1,this.beforeDrainCallback=null,this._lastSentQoeKpis={},this.timer=X({interval:this.harvestCycle,onTick:()=>this.onHarvestInterval(),errorLabel:"HarvestScheduler"}),this.setupPageLifecycleHandlers()}get isStarted(){return this.timer.isRunning()}startScheduler(){this.timer.isRunning()?n.warn("Harvest scheduler is already started"):(n.notice("Starting harvest scheduler",{harvestCycle:this.harvestCycle,eventBufferSize:this.eventBuffer?this.eventBuffer.size():0}),this.timer.start())}stopScheduler(){this.timer.isRunning()&&(this.timer.stop(),n.notice("Harvest scheduler stopped"))}async triggerSmartHarvest(e,t){if(n.notice(`${e} harvest triggered at ${t}% threshold`,{type:e,threshold:t}),this.eventBuffer&&!this.eventBuffer.isEmpty())try{await this.triggerHarvest({})}catch(t){n.error(`${e} harvest failed:`,t.message)}finally{this.timer.cancelAndReschedule()}}async onHarvestInterval(){const e=this.eventBuffer&&!this.eventBuffer.isEmpty(),t=this.retryQueueHandler&&this.retryQueueHandler.getQueueSize()>0;(e||t)&&await this.triggerHarvest({})}async triggerHarvest(e={}){if(this.isHarvesting)return{success:!1,reason:"harvest_in_progress"};this.isHarvesting=!0;try{let t=this.drainEvents(e);if(e.isFinalHarvest){const e=h.MAX_BEACON_SIZE;v(t)>e&&(t=this.trimEventsToFit(t,e))}const i=await this.sendChunk(t,e,!0);return{success:i.success,totalChunks:1,results:[i]}}catch(e){return n.error("Harvest cycle failed:",e.message),this.handleHarvestFailure(e),{success:!1,error:e.message}}finally{this.isHarvesting=!1}}trimEventsToFit(e,t){if(0===e.length)return e;const i=[];let s=0;for(let r=e.length-1;r>=0;r--){const a=e[r],n=v({ins:[a,...i]});n>t||(i.unshift(a),s=n)}const r=e.length-i.length;if(r>0){const a=e.slice(0,r);n.warn(`Discarded ${r} events to fit beacon size limit`,{originalCount:e.length,trimmedCount:i.length,finalSize:s,maxSize:t}),this.retryQueueHandler&&this.retryQueueHandler.addFailedEvents(a)}return i}drainEvents(e={}){const t=window.NRVIDEO?.config?.qoeIntervalFactor??1,i=!!e.isFinalHarvest||this.forceNextQoeCycle,s=(this.qoeCycleCount-1)%t==0||i;if(this.forceNextQoeCycle&&(this.forceNextQoeCycle=!1),this.beforeDrainCallback&&"function"==typeof this.beforeDrainCallback)try{this.beforeDrainCallback()}catch(e){n.error("Before drain callback failed:",e.message)}let r=W(this.eventBuffer.drain(),s,this.eventBuffer);this.qoeCycleCount++,Y(r,this._lastSentQoeKpis,i);let a=[...r],o=v(r);if(this.retryQueueHandler&&this.retryQueueHandler.getQueueSize()>0){const e=h.MAX_PAYLOAD_SIZE-o,t=h.MAX_EVENTS_PER_BATCH-a.length;if(e>0&&t>0){const i=this.retryQueueHandler.getRetryEventsToFit(e,t);i.length>0&&(a=[...i,...a])}}return a}async sendChunk(e,t,i){const s={url:function(e){try{if(!window.NRVIDEO||!window.NRVIDEO.info)throw new Error("NRVIDEO info is not available.");let{beacon:t,licenseKey:i,applicationID:s}=window.NRVIDEO.info;if(!t||!i)throw new Error("Options object provided by New Relic is not correctly initialized");return s?`https://${e||t}/ins/1/${i}?a=${s}&v=${l}&ref=${window.location.href}&ca=VA`:`https://${e||t}/ins/1/${i}?&v=${l}&ref=${window.location.href}&ca=VA`}catch(e){return console.error(e.message),null}}(this.fallBackUrl),payload:{body:{ins:e}},options:{...t,isLastChunk:i}};return new Promise(t=>{this.httpClient.send(s,i=>{i.retry?this.handleRequestFailure(e):(this.retryCount=0,this.fallBackUrl=""),t({success:!i.retry,status:i.status,error:i.error,chunk:e,eventCount:e.length})})})}handleRequestFailure(e){this.retryQueueHandler.addFailedEvents(e),"US"===window.NRVIDEO?.info?.region&&(this.retryCount++,this.retryCount>5?(this.retryCount=0,this.fallBackUrl=""):this.retryCount>=2&&(this.fallBackUrl=h.COLLECTOR.US[1]))}handleHarvestFailure(e){n.warn("Harvest failure handled",{error:e.message})}updateHarvestInterval(e){"number"!=typeof e||isNaN(e)?n.warn("Invalid newInterval provided to updateHarvestInterval"):e<1e3||e>3e5?n.warn("newInterval out of bounds (1000-300000), ignoring"):this.harvestCycle!==e&&(this.harvestCycle=e,n.notice("Updated harvestCycle:",this.harvestCycle),this.timer.updateInterval(e))}setupPageLifecycleHandlers(){let e=!1;const t=()=>{e||(e=!0,this.triggerHarvest({isFinalHarvest:!0,force:!0}))};document.addEventListener("visibilitychange",()=>{document.hidden&&t()}),window.addEventListener("pagehide",()=>{t()}),window.addEventListener("beforeunload",()=>{t()})}}const J=new class{constructor(){this.isInitialized=!1,this.harvestScheduler=null,this.eventBuffer=null}initialize(){if(this.isInitialized)n.warn("Video analytics agent already initialized");else try{this.eventBuffer=new x,this.harvestScheduler=new Z(this.eventBuffer),this.harvestScheduler.startScheduler(),this.isInitialized=!0,n.notice("Video analytics agent initialized successfully")}catch(e){n.error("Failed to initialize video analytics agent:",e.message)}}addEvent(e){this.isInitialized||(n.warn("Video analytics agent not initialized, initializing now"),this.initialize());try{return G(this.eventBuffer,e)}catch(e){return n.error("Failed to add event to harvesting system:",e.message),!1}}setHarvestInterval(e){this.isInitialized||this.initialize(),this.harvestScheduler.updateHarvestInterval(e)}forceNextQoeCycle(){this.harvestScheduler&&(this.harvestScheduler.forceNextQoeCycle=!0)}setBeforeDrainCallback(e){this.harvestScheduler&&(this.harvestScheduler.beforeDrainCallback=e)}refreshQoeKpis(e,t){K(this.eventBuffer,e,t)}};A("Browser",J);const ee=J;class te{constructor({accountId:e,applicationToken:t,endpoint:i,deviceInfo:s}={}){if(!t)throw new Error("applicationToken is required");const r=i?.toLowerCase();if(!(r in S))throw new Error("Invalid endpoint");this.accountId=e,this.applicationToken=t,this.endpoint=r,this.harvestInterval=6e4,this.maxBufferSize=100,s||n.warn("ConnectedDeviceHarvester: no deviceInfo provided — using placeholder defaults. Pass info.deviceInfo for accurate device data.");const{uuid:a,osVersion:o,deviceModel:h,deviceManufacturer:l,osBuild:d,appBuild:c,architecture:u}=s??{};this.deviceInfo={uuid:a||B[5],osVersion:o||B[1],deviceModel:h||B[2],deviceManufacturer:l||B[8],osBuild:d||b.osBuild,appBuild:c||b.appBuild,architecture:u||b.architecture},this.eventBuffer=new x,this.eventBuffer.setSmartHarvestCallback((e,t)=>this.triggerSmartHarvest(e,t)),this.dataToken=null,this.isHarvesting=!1,this.isDisposed=!1,this._isFetchingToken=!1,this.timer=X({interval:this.harvestInterval,onTick:()=>this.sendBufferedEvents(),errorLabel:"ConnectedDeviceHarvester"}),this.qoeCycleCount=1,this.forceQoeNextCycle=!1,this.beforeDrainCallback=null,this._lastSentQoeKpis={},this._connectAttempt=0,this.initialise()}getEndpointBaseUrl(){return S[this.endpoint]??S.us}async initialise(){await this.fetchDataTokens(),this.isDisposed||this.dataToken&&this.startHarvestInterval()}async fetchDataTokens(){if(!this._isFetchingToken){this._isFetchingToken=!0;try{for(let e=0;e<3;e++){if(this.isDisposed)return;const t=`${this.getEndpointBaseUrl()}/v5/connect`;try{n.notice(`ConnectedDeviceHarvester: POST ${t} (attempt ${e+1}/3)`);const i=await this._fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json","X-App-License-Key":this.applicationToken},body:JSON.stringify(_)},1e4);if(!i.ok){let e="";try{e=await i.text()}catch(e){}throw new Error(`HTTP ${i.status} body=${e}`)}const s=await i.json();if(!s||!s.data_token)throw new Error("Missing data_token in connect response");return this.dataToken=s.data_token,this._connectAttempt=e+1,void n.notice("ConnectedDeviceHarvester: dataToken acquired")}catch(t){if(this._connectAttempt=e+1,n.error(`ConnectedDeviceHarvester: /v5/connect failed (attempt ${this._connectAttempt}/3):`,t.message),e>=2)return void n.error("ConnectedDeviceHarvester: Max retries reached — dataToken stays null");await new Promise(e=>setTimeout(e,1e4))}}}finally{this._isFetchingToken=!1}}}startHarvestInterval(){this.isDisposed||this.timer.start()}async triggerSmartHarvest(e,t){if(n.notice(`ConnectedDeviceHarvester: smart-harvest trigger (${e} at ${t}%)`),this.eventBuffer&&!this.eventBuffer.isEmpty())try{await this.sendBufferedEvents()}catch(t){n.error(`${e} smart-harvest failed:`,t.message)}finally{this.timer.cancelAndReschedule()}}addEvent(e){try{return G(this.eventBuffer,e)}catch(e){return n.error("ConnectedDeviceHarvester.addEvent failed:",e.message),!1}}forceQoeNextHarvest(){this.forceQoeNextCycle=!0}setBeforeDrainCallback(e){"function"!=typeof e&&null!==e||(this.beforeDrainCallback=e)}refreshQoeKpis(e,t){K(this.eventBuffer,e,t)}setHarvestInterval(e){"number"!=typeof e||e<=0||(this.harvestInterval=e,this.timer.updateInterval(e))}async sendBufferedEvents(){if(this.isHarvesting)return;if(!this.dataToken)return;if(this.eventBuffer.isEmpty())return;if("function"==typeof this.beforeDrainCallback)try{this.beforeDrainCallback()}catch(e){n.error("ConnectedDeviceHarvester beforeDrainCallback failed:",e.message)}this.isHarvesting=!0;const e=this.eventBuffer.drain(),t=globalThis.__NRVIDEO_CD__?.config?.qoeIntervalFactor??1,i=this.forceQoeNextCycle,s=(this.qoeCycleCount-1)%t==0||i;this.forceQoeNextCycle&&(this.forceQoeNextCycle=!1);const r=W(e,s,this.eventBuffer);if(this.qoeCycleCount++,Y(r,this._lastSentQoeKpis,i),0===r.length)return void(this.isHarvesting=!1);const a=`${this.getEndpointBaseUrl()}/v3/data`,o={"Content-Type":"application/json","X-App-License-Key":this.applicationToken},h=()=>U(JSON.stringify([this.dataToken,this._buildDeviceInfo(),0,[],[],[],[],[],this._buildMetadata(),r]),globalThis.__NRVIDEO_CD__?.config?.obfuscate);try{let e=await this._fetchWithTimeout(a,{method:"POST",headers:o,body:h()},3e4);if(401===e.status){n.notice("ConnectedDeviceHarvester: /v3/data returned 401 — re-queuing events and reconnecting"),this.dataToken=null,this._connectAttempt=0;for(const e of r)this.eventBuffer.add(e);return void this.initialise()}if(!e.ok)throw new Error(`HTTP ${e.status}`);n.notice(`ConnectedDeviceHarvester: sent ${r.length} events`)}catch(e){n.error("ConnectedDeviceHarvester: /v3/data send failed:",e.message);for(const e of r)this.eventBuffer.add(e)}finally{this.isHarvesting=!1}}_buildDeviceInfo(){const e=this.deviceInfo;return[B[0],e.osVersion,e.deviceModel,B[3],B[4],e.uuid,"","",e.deviceManufacturer,B[9]]}_buildMetadata(){const e=this.deviceInfo;return{...b,osBuild:e.osBuild,appBuild:e.appBuild,architecture:e.architecture}}_fetchWithTimeout(e,t,i){const s=new AbortController,r=setTimeout(()=>s.abort(),i);return fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r))}async dispose(){return this.isDisposed=!0,this.timer.stop(),this.sendBufferedEvents()}}const ie=new class{constructor(){this.isInitialized=!1,this.harvester=null}initialize(){if(this.isInitialized)return;const e=globalThis.__NRVIDEO_CD__?.info;if(e)try{this.harvester=new te(e),this.isInitialized=!0,n.notice("ConnectedDeviceAnalyticsAgent initialized")}catch(e){n.error("ConnectedDeviceAnalyticsAgent.initialize failed:",e.message)}else n.warn("ConnectedDeviceAnalyticsAgent.initialize: globalThis.__NRVIDEO_CD__.info is missing")}addEvent(e){return this.isInitialized||this.initialize(),!!this.isInitialized&&this.harvester.addEvent(e)}forceQoeNextHarvest(){this.harvester&&this.harvester.forceQoeNextHarvest()}forceNextQoeCycle(){this.forceQoeNextHarvest()}setBeforeDrainCallback(e){this.harvester&&this.harvester.setBeforeDrainCallback(e)}refreshQoeKpis(e,t){this.isInitialized||this.initialize(),this.harvester&&this.harvester.refreshQoeKpis(e,t)}setHarvestInterval(e){this.isInitialized||this.initialize(),this.harvester&&this.harvester.setHarvestInterval(e)}};A("Vega",ie);const se=ie,re={Constants:h,Chrono:u,Log:n,Emitter:d,Tracker:g,VideoTracker:H,VideoTrackerState:O,Core:I,version:l,NrVideoEventAggregator:x,RetryQueueHandler:z,OptimizedHttpClient:M,HarvestScheduler:Z,recordEvent:y};module.exports=t})();
2
+ (()=>{"use strict";const e={d:(t,i)=>{if(Array.isArray(i))for(var s=0;s<i.length;){var r=i[s++],a=i[s++];e.o(t,r)?0===a&&s++:0===a?Object.defineProperty(t,r,{enumerable:!0,value:i[s++]}):Object.defineProperty(t,r,{enumerable:!0,get:a})}else for(var r in i)e.o(i,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:i[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{connectedDeviceAnalyticsHarvester:()=>ie,default:()=>se,getRegisteredHarvester:()=>A,videoAnalyticsHarvester:()=>J});class i{static Levels;static level;static colorful;static includeTime;static prefix;static error(...e){s(e,i.Levels.ERROR,"darkred")}static warn(...e){s(e,i.Levels.WARNING,"darkorange")}static notice(...e){s([].slice.call(arguments),i.Levels.NOTICE,"darkcyan")}static debug(...e){s(e,i.Levels.DEBUG,"indigo")}static debugCommonVideoEvents(e,t,s){try{if(i.level<=i.Levels.DEBUG){s=s||function(e){i.debug("Event: "+e.type)};var r=["canplay","buffering","waiting","ended","play","playing","pause","resume","error","abort","seek","seeking","seeked","stalled","dispose","loadeddata","loadstart","loadedmetadata"];t&&(null===t[0]?(t.shift(),r=t):r=r.concat(t));for(var a=0;a<r.length;a++)"function"==typeof e?e.call(window,r[a],s):e.on?e.on(r[a],s):e.addEventListener?e.addEventListener(r[a],s):e.addEventHandler?e.addEventHandler(r[a],s):i.warn("debugCommonVideoEvents: No common listener function found for ",e)}}catch(e){i.warn(e)}}}function s(e,t,s){t=t||i.Levels.NOTICE,s=s||"darkcyan";var n,o,l,h,d,c,u=i.prefix;(i.includeTime&&(u+=(n=new Date,o=("0"+n.getDate()).slice(-2),l=("0"+n.getMinutes()).slice(-2),h=("0"+n.getSeconds()).slice(-2),d=("00"+n.getMilliseconds()).slice(-3),"["+o+":"+l+":"+h+"."+d+"] ")),u+=function(e){return a[e]}(t)+":",i.level<=t&&t!==i.Levels.SILENT)&&(!i.colorful||"undefined"!=typeof document&&document.documentMode?r(e,u):(c=t===i.Levels.ERROR&&console.error?console.error:t===i.Levels.WARNING&&console.warn?console.warn:t===i.Levels.DEBUG&&console.debug&&null==window.cast?console.debug:console.log,u="%c"+u,e.splice(0,0,u,"color: "+s),c.apply(console,e)))}function r(e,t){if(e instanceof Array)for(var i in e)r(e[i],t);else"string"==typeof e?console.log(t+" "+e):(console.log(t+"↵"),console.log(e))}i.Levels={SILENT:5,ERROR:4,WARNING:3,NOTICE:2,DEBUG:1,ALL:0},i.level=i.Levels.ERROR,i.colorful=!0,i.includeTime=!0,i.prefix="[nrvideo]";const a={4:"e",3:"w",2:"n",1:"d"};!function(){if("undefined"!=typeof window&&window.location&&window.location.search){var e=/\?.*&*nrvideo-debug=(.+)/i.exec(window.location.search);null!==e&&("true"===e[1]?i.level=i.Levels.ALL:i.level=e[1]),null!==/\?.*&*nrvideo-colors=false/i.exec(window.location.search)&&(i.colorful=!1)}}();const n=i;const o=class{static AdPositions={PRE:"pre",MID:"mid",POST:"post"};static COLLECTOR={US:["bam.nr-data.net","bam-cell.nr-data.net"],EU:"bam.eu01.nr-data.net",JP:"bam.jp.nr-data.net",Staging:"staging-bam-cell.nr-data.net",GOV:"gov-bam.nr-data.net"};static VALID_EVENT_TYPES=["VideoAction","VideoAdAction","VideoErrorAction","VideoCustomAction"];static MAX_PAYLOAD_SIZE=1048576;static MAX_BEACON_SIZE=61440;static MAX_EVENTS_PER_BATCH=1e3;static INTERVAL=1e4;static DEFAULT_QOE_INTERVAL_FACTOR=2;static QOE_KPI_KEYS=["startupTime","peakBitrate","averageBitrate","totalPlaytime","totalRebufferingTime","rebufferingRatio","hadStartupError","hadPlaybackError","numberOfErrors"];static QOE_AGGREGATE_KEYS=["coreVersion","instrumentation.name","instrumentation.provider","instrumentation.version","isBackgroundEvent","playerName","playerVersion","src","viewId","viewSession","contentIsAutoplayed","contentIsMuted","contentRenditionHeight","contentRenditionWidth","contentSrc","numberOfVideos","pageUrl","trackerName","trackerVersion","contentDuration","contentPlayrate","contentPlayhead","contentPreload","elapsedTime","contentTitle","contentId","contentIsLive","deviceType","deviceGroup","deviceManufacturer","deviceModel","deviceName","deviceSize","deviceUuid","contentRenditionName","contentIsFullscreen","contentCdn","contentFps","asnOrganization","asnLongitude","asnLatitude","asn","timeSinceRequested","timeSinceStarted"]},l="5.1.0";const h=class{_listeners;on(e,t){if(this._listeners=this._listeners||{},"function"==typeof t)return this._listeners[e]=this._listeners[e]||[],this._listeners[e].push(t),this}off(e,t){if(this._listeners=this._listeners||{},this._listeners[e]){var i=this._listeners[e].indexOf(t);-1!==i&&this._listeners[e].splice(i,1)}return this}emit(e,t,i){return this._listeners=this._listeners||{},i=i||{},Array.isArray(this._listeners[t])&&this._listeners[t].forEach(s=>{s.call(this,{eventType:e,type:t,data:i,target:this})}),Array.isArray(this._listeners["*"])&&this._listeners["*"].forEach(s=>{s.call(this,{eventType:e,type:t,data:i,target:this})}),this}};class d{startTime=0;stopTime=0;accumulator=0;offset=0;constructor(){this.reset()}reset(){this.startTime=0,this.stopTime=0,this.accumulator=0,this.offset=0}getDeltaTime(){return this.startTime?this.offset+((new Date).getTime()-this.startTime):null}start(){this.startTime=(new Date).getTime(),this.stopTime=0}stop(){return this.stopTime=(new Date).getTime(),this.startTime<this.stopTime&&(this.accumulator+=this.stopTime-this.startTime),this.getDeltaTime()}getDuration(){return this.stopTime?this.accumulator+this.offset:this.accumulator+(this.getDeltaTime()??0)}clone(){var e=new d;return e.startTime=this.startTime,e.stopTime=this.stopTime,e.offset=this.offset,e.accumulator=this.accumulator,e}}const c=d;class u extends h{static Events;customData;heartbeat;parentTracker;state;_trackerReadyChrono;_actionTable;_actionAdTable;_heartbeatInterval;constructor(e){super(),this.customData={},this.heartbeat=null,this.parentTracker=null,this._trackerReadyChrono=new c,this._trackerReadyChrono.start(),this._actionTable=o.ACTION_TABLE,this._actionAdTable=o.ACTION_AD_TABLE,e=e||{},this.setOptions(e)}setOptions(e){e&&(e.parentTracker&&(this.parentTracker=e.parentTracker),e.customData&&(this.customData=e.customData),e.heartbeat&&(this.heartbeat=e.heartbeat))}dispose(){this.unregisterListeners()}registerListeners(){}unregisterListeners(){}getHeartbeat(){return this.state?._isAd?2e3:this.heartbeat?this.heartbeat:this.parentTracker&&this.parentTracker.heartbeat?this.parentTracker.heartbeat:3e4}startHeartbeat(){this._heartbeatInterval=setInterval(this.sendHeartbeat.bind(this),Math.max(this.getHeartbeat(),2e3))}stopHeartbeat(){this._heartbeatInterval&&clearInterval(this._heartbeatInterval)}sendHeartbeat(e){this.sendVideoAction(u.Events.HEARTBEAT,e)}getAttributes(e,t){(e=e||{}).trackerName=this.getTrackerName(),e.trackerVersion=this.getTrackerVersion(),e.coreVersion=l,e.timeSinceTrackerReady=this._trackerReadyChrono.getDeltaTime();for(let t in this.customData)e[t]=this.customData[t];return null!=document.hidden&&(e.isBackgroundEvent=document.hidden),e}getTrackerVersion(){return l}getTrackerName(){return"base-tracker"}sendVideoAction(e,t){this.emit("VideoAction",e,this.getAttributes(t))}sendVideoAdAction(e,t){this.emit("VideoAdAction",e,this.getAttributes(t))}sendVideoErrorAction(e,t){let i=this.isAd()?"adError":"videoError";this.emit("VideoErrorAction",e,this.getAttributes(t,i))}sendVideoCustomAction(e,t){this.emit("VideoCustomAction",e,this.getAttributes(t,"customAction"))}setHarvestInterval(e){const t=this.getHarvester?.();if(t)try{t.setHarvestInterval(e)}catch(e){return void n.error("Failed to set harvest interval:",e.message)}else n.error("Tracker has no harvester; setHarvestInterval ignored")}getHarvester(){return null}}u.Events={HEARTBEAT:"HEARTBEAT",QOE_AGGREGATE:"QOE_AGGREGATE"};const f=u;function g(e){try{return JSON.stringify(e,(()=>{const e=new WeakSet;return(t,i)=>{if("object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})())??""}catch(e){return n.error("Error stringifying value:",e.message),""}}function m(e){if("string"==typeof e&&e.length)return e.length;if("object"==typeof e){if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer&&e.byteLength)return e.byteLength;if("undefined"!=typeof Blob&&e instanceof Blob&&e.size)return e.size;if(!("undefined"!=typeof FormData&&e instanceof FormData))try{return g(e).length}catch(e){return}}}function v(e,t,i,{addTimeSinceLoad:s=!1}={}){const{appName:r,applicationID:a}=i,{qoe:n,...l}=t,h=n?{...n}:{},d={...a?{}:{appName:r},timestamp:Date.now(),...s?{timeSinceLoad:"undefined"!=typeof window&&window.performance?window.performance.now()/1e3:null}:{}},c={...l,eventType:e,...d};let u=null;if("VideoAction"===e){const e=(g=o.QOE_AGGREGATE_KEYS,m=t,g&&Array.isArray(g)&&0!==g.length?m&&"object"==typeof m?g.reduce((e,t)=>(t in m&&(e[t]=m[t]),e),{}):{}:m);u={eventType:"VideoAction",actionName:f.Events.QOE_AGGREGATE,qoeAggregateVersion:"1.0.0",...h,...e,...d}}var g,m;return{eventObject:c,qoeEventObject:u}}const T=Object.create(null);function E(e,t){T[e]=t}function A(e){return T[e]}function p(e,t={}){try{if(!o.VALID_EVENT_TYPES.includes(e))return n.warn("Invalid event type provided to recordEvent",{eventType:e}),!1;const i="Vega"===t.src,s=i?"Vega":"Browser",r="undefined"!=typeof window?window:void 0,a=i?globalThis.__NRVIDEO_CD__?.info:r?.NRVIDEO?.info;if(!a)return;const l=T[s];if(!l)return n.warn("No harvester registered for routing key",{routingKey:s}),!1;return function(e,t,i,s,r,{addTimeSinceLoad:a=!1}={}){if(!s)return!1;const{eventObject:n,qoeEventObject:o}=v(e,t,i,{addTimeSinceLoad:a}),l=s.addEvent(n);return o&&r?l&&s.addEvent(o):l}(e,t,a,l,!!(i?globalThis.__NRVIDEO_CD__?.config?.qoeAggregate:r?.NRVIDEO?.config?.qoeAggregate),{addTimeSinceLoad:!i})}catch(e){return n.error("Failed to record event:",e.message),!1}}const S={us:"https://mobile-collector.newrelic.com/mobile",eu:"https://mobile-collector.eu01.nr-data.net/mobile",staging:"https://staging-mobile-collector.newrelic.com/mobile",gov:"https://gov-mobile-collector.newrelic.com/mobile",jp:"https://mobile-collector.jp.nr-data.net/mobile"},y=[["newrelic_mobile_example","1.1","com.newrelic.newrelic_mobile_example"],["Android","14","sdk_gphone64_arm64","AndroidAgent","7.4.0-alpha01","b797aee6-aa69-4879-9ba3-1f4aed1a7777","","","Google",{size:"normal",platform:"Flutter",platformVersion:"1.0.8"}]],_=["Vega","1.0","VegaDevice","VegaAgent","1.0.0","00000000-0000-0000-0000-000000000000","","","Amazon",{size:"normal",platform:"Native",platformVersion:"1.0.0"}],B={osBuild:"1",osName:"Vega",platform:"Native",appBuild:"1",architecture:"aarch64"},{COLLECTOR:b}=o;class R{setConfiguration(e,t,i){return!!("Vega"===i?this.validateVegaFields(e):this.validateRequiredFields(e))&&(!!this.validateConfigFields(t)&&(this.initializeGlobalConfig(e,t,i),n.notice("Video analytics configuration initialized successfully"),!0))}validateVegaFields(e){return e&&"object"==typeof e?e.applicationToken?e.endpoint?.toLowerCase()in S||(n.error("Invalid endpoint (must be us, eu, staging, gov, or jp)"),!1):(n.error("applicationToken is required"),!1):(n.error("Configuration must be an object"),!1)}validateRequiredFields(e){if(!e||"object"!=typeof e)return n.error("Configuration must be an object"),!1;const{licenseKey:t,appName:i,region:s,applicationID:r,beacon:a}=e;if(!t)return n.error("licenseKey is required"),!1;if(r){if(!a)return n.error("beacon is required when applicationID is provided"),!1;if(!Object.values(b).flatMap(e=>e).includes(a))return n.error(`Invalid beacon: ${a}`),!1}else{if(!i||!s)return n.error("appName and region are required when applicationID is not provided"),!1;if(!b[s])return n.error(`Invalid region: ${s}. Valid regions are: ${Object.keys(b).join(", ")}`),!1}return!0}validateConfigFields(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return n.error("config must be an object"),!1;const{qoeAggregate:t,obfuscate:i}=e;return void 0!==t&&"boolean"!=typeof t?(n.error("qoeAggregate must be a boolean"),!1):!(void 0!==i&&!Array.isArray(i))||(n.error("obfuscate must be an array"),!1)}filterObfuscateRules(e){return e?e.filter(e=>{const t=void 0!==e.regex&&("string"==typeof e.regex||e.regex instanceof RegExp),i=void 0!==e.replacement&&"string"==typeof e.replacement;return!(!t||!i)||(n.warn("obfuscate rule missing required 'regex' (string|RegExp) and/or 'replacement' (string), skipping:",e),!1)}):[]}sanitizeQoeIntervalFactor(e){return null==e?o.DEFAULT_QOE_INTERVAL_FACTOR:"number"==typeof e&&Number.isInteger(e)&&e>=1?e:(n.warn(`Invalid qoeIntervalFactor "${e}" — must be a positive integer. Defaulting to ${o.DEFAULT_QOE_INTERVAL_FACTOR}.`),o.DEFAULT_QOE_INTERVAL_FACTOR)}initializeGlobalConfig(e,t,i){if("Vega"===i)return void(globalThis.__NRVIDEO_CD__={info:{accountId:e.accountId,applicationToken:e.applicationToken,endpoint:e.endpoint?.toLowerCase(),...e.appName?{appName:e.appName}:{},...e.applicationID?{applicationID:e.applicationID}:{},...e.deviceInfo?{deviceInfo:e.deviceInfo}:{}},config:{qoeAggregate:t?.qoeAggregate??!0,qoeIntervalFactor:this.sanitizeQoeIntervalFactor(t?.qoeIntervalFactor),obfuscate:this.filterObfuscateRules(t?.obfuscate)}});let{licenseKey:s,appName:r,region:a,beacon:n,applicationID:l}=e;n="US"===a?o.COLLECTOR.US[0]:n||b[a],window.NRVIDEO={info:{...a?{region:a}:{},beacon:n,licenseKey:s,applicationID:l,...l?{}:{appName:r}},config:{qoeAggregate:t?.qoeAggregate??!0,qoeIntervalFactor:this.sanitizeQoeIntervalFactor(t?.qoeIntervalFactor),obfuscate:this.filterObfuscateRules(t?.obfuscate)}}}}const w=new R;class D{static addTracker(e,t){t?.info&&function(e,t,i){w.setConfiguration(e,t,i)}(t.info,t?.config,t?.src),e.on&&e.emit?(k.push(e),e.on("*",C),"function"==typeof e.trackerInit&&e.trackerInit()):n.error("Tried to load a non-tracker.",e)}static removeTracker(e){e.off("*",C),e.dispose();let t=k.indexOf(e);-1!==t&&k.splice(t,1)}static getTrackers(){return k}static send(e,t,i){return p(e,{actionName:t,...i})}static sendError(e){return p("VideoErrorAction",{actionName:"ERROR",...e})}}let k=[];function C(e){try{let t=function(e){let t={};for(let i in e)null!==e[i]&&void 0!==e[i]&&(t[i]=e[i]);return t}(e.data);n.level<=n.Levels.DEBUG?n.notice("Sent",e.type,t):n.notice("Sent",e.type),D.send(e.eventType,e.type,t)}catch(e){n.error("Error in event handler:",e.message)}}const N=D;const I=class{_viewSession=null;_viewCount=0;_isAd=!1;numberOfErrors=0;numberOfAds=0;numberOfVideos=0;totalPlaytime=0;weightedAverageBitrate=0;totalAdPlaytime=0;isAdBreak=!1;initialBufferingHappened=!1;startupTime=null;peakBitrate=0;partialAverageBitrate=0;_totalBitrateDuration=0;weightedBitrate=0;_lastBitrate=null;_lastBitrateChangeTimestamp=null;_downloadBitrates=[];_lastDownloadBitrate=null;totalSwitchUps=0;totalSwitchDowns=0;totalPauseTime=0;_playedRenditions=new Set;hadStartupError=!1;hadPlaybackError=!1;totalRebufferingTime=0;isPlayerReady=!1;isRequested=!1;isStarted=!1;isPaused=!1;isSeeking=!1;isBuffering=!1;isPlaying=!1;timeSinceRequested;timeSinceStarted;timeSincePaused;timeSinceSeekBegin;timeSinceBufferBegin;timeSinceAdBreakStart;timeSinceLastDownload;timeSinceLastHeartbeat;timeSinceLastRenditionChange;timeSinceLastAdQuartile;timeSinceLastAd;timeSinceLastError;timeSinceLastAdError;timeSinceResumed;timeSinceSeekEnd;playtimeSinceLastEvent;customTimeSinceAttributes={};elapsedTime;bufferElapsedTime;_totalAdPlaytime;_createdAt;_hb;_acc;_bufferAcc;isError;constructor(){this.reset(),this._createdAt=Date.now(),this._hb=!0,this._acc=0,this._bufferAcc=0}reset(){this._viewSession=null,this._viewCount=0,this._isAd=!1,this.numberOfErrors=0,this.numberOfAds=0,this.numberOfVideos=0,this.totalPlaytime=0,this.weightedAverageBitrate=0,this.totalAdPlaytime=0,this.isAdBreak=!1,this.initialBufferingHappened=!1,this.startupTime=null,this.peakBitrate=0,this.partialAverageBitrate=0,this._totalBitrateDuration=0,this.weightedBitrate=0,this._lastBitrate=null,this._lastBitrateChangeTimestamp=null,this._downloadBitrates=[],this._lastDownloadBitrate=null,this.totalSwitchUps=0,this.totalSwitchDowns=0,this.totalPauseTime=0,this._playedRenditions=new Set,this.hadStartupError=!1,this.hadPlaybackError=!1,this.totalRebufferingTime=0,this.resetFlags(),this.resetChronos()}resetFlags(){this.isPlayerReady=!1,this.isRequested=!1,this.isStarted=!1,this.isPaused=!1,this.isSeeking=!1,this.isBuffering=!1,this.isPlaying=!1}resetChronos(){this.timeSinceRequested=new c,this.timeSinceStarted=new c,this.timeSincePaused=new c,this.timeSinceSeekBegin=new c,this.timeSinceBufferBegin=new c,this.timeSinceAdBreakStart=new c,this.timeSinceLastDownload=new c,this.timeSinceLastHeartbeat=new c,this.timeSinceLastRenditionChange=new c,this.timeSinceLastAdQuartile=new c,this.timeSinceLastAd=new c,this.timeSinceLastError=new c,this.timeSinceLastAdError=new c,this.timeSinceResumed=new c,this.timeSinceSeekEnd=new c,this.playtimeSinceLastEvent=new c,this.customTimeSinceAttributes={},this.elapsedTime=new c,this.bufferElapsedTime=new c,this._totalAdPlaytime=new c}isAd(){return this._isAd}setIsAd(e){this._isAd=e}setTimeSinceAttribute(e){this.customTimeSinceAttributes[e]=new c,this.customTimeSinceAttributes[e].start()}removeTimeSinceAttribute(e){delete this.customTimeSinceAttributes[e]}getViewSession(){if(!this._viewSession){let e=(new Date).getTime(),t=Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2);this._viewSession=e+"-"+t}return this._viewSession}getViewId(){return this.getViewSession()+"-"+this._viewCount}getStateAttributes(e){e=e||{},this.isAd()?(this.isRequested&&(e.timeSinceAdRequested=this.timeSinceRequested.getDeltaTime(),e.timeSinceLastAdHeartbeat=this.timeSinceLastHeartbeat.getDeltaTime()),this.isStarted&&(e.timeSinceAdStarted=this.timeSinceStarted.getDeltaTime()),this.isPaused&&(e.timeSinceAdPaused=this.timeSincePaused.getDeltaTime()),this.isBuffering&&(e.timeSinceAdBufferBegin=this.timeSinceBufferBegin.getDeltaTime()),this.isSeeking&&(e.timeSinceAdSeekBegin=this.timeSinceSeekBegin.getDeltaTime()),this.isAdBreak&&(e.timeSinceAdBreakBegin=this.timeSinceAdBreakStart.getDeltaTime()),this.numberOfErrors>0&&this.timeSinceLastAdError.startTime>0&&(e.timeSinceLastAdError=this.timeSinceLastAdError.getDeltaTime()),e.numberOfAds=this.numberOfAds):(this.isRequested&&(e.timeSinceRequested=this.timeSinceRequested.getDeltaTime(),e.timeSinceLastHeartbeat=this.timeSinceLastHeartbeat.getDeltaTime()),this.isStarted&&(e.timeSinceStarted=this.timeSinceStarted.getDeltaTime()),this.isPaused&&(e.timeSincePaused=this.timeSincePaused.getDeltaTime()),this.isBuffering&&(e.timeSinceBufferBegin=this.timeSinceBufferBegin.getDeltaTime()),this.isSeeking&&(e.timeSinceSeekBegin=this.timeSinceSeekBegin.getDeltaTime()),e.timeSinceLastAd=this.timeSinceLastAd.getDeltaTime(),this.numberOfErrors>0&&this.timeSinceLastError.startTime>0&&(e.timeSinceLastError=this.timeSinceLastError.getDeltaTime()),e.numberOfVideos=this.numberOfVideos),e.numberOfErrors=this.numberOfErrors,this.isAd()||(this.playtimeSinceLastEvent.startTime>0?e.playtimeSinceLastEvent=this.playtimeSinceLastEvent.getDeltaTime():e.playtimeSinceLastEvent=0,this.isPlaying?this.playtimeSinceLastEvent.start():this.playtimeSinceLastEvent.reset(),this.totalPlaytime+=e.playtimeSinceLastEvent,e.totalPlaytime=this.totalPlaytime);for(const[t,i]of Object.entries(this.customTimeSinceAttributes))e[t]=i.getDeltaTime();return e}getQoeAttributes(e){e=e||{};const t={};try{if(null!==this.startupTime&&(t.startupTime=this.startupTime),this.peakBitrate>0&&(t.peakBitrate=this.peakBitrate),t.hadStartupError=this.hadStartupError,t.hadPlaybackError=this.hadPlaybackError,t.totalRebufferingTime=this.totalRebufferingTime,t.rebufferingRatio=this.totalPlaytime>0?this.totalRebufferingTime/this.totalPlaytime*100:0,t.totalPlaytime=this.totalPlaytime,t.averageBitrate=this.weightedBitrate,t.numberOfErrors=this.numberOfErrors,this._downloadBitrates.length>0){const e=this._downloadBitrates.reduce((e,t)=>e+t,0);t.avgDownloadRate=Math.round(e/this._downloadBitrates.length),t.minDownloadRate=Math.min(...this._downloadBitrates),t.maxDownloadRate=Math.max(...this._downloadBitrates)}t.totalSwitchUps=this.totalSwitchUps,t.totalSwitchDowns=this.totalSwitchDowns,t.totalPauseTime=this.timeSincePaused.getDuration(),t.totalViewSessionTime=this.totalPlaytime,t.totalRenditions=this._playedRenditions.size,t.qoeAggregateVersion="1.1.0"}catch(e){n.error("Failed to add attributes for QOE KPIs",e.message)}return e.qoe=t,e}calculateBufferType(e){let t="";return t=e?"initial":this.isSeeking?"seek":this.isPaused?"pause":"connection",n.debug("Buffer Type = "+t),t}goViewCountUp(){this._viewCount++}goPlayerReady(){return!this.isPlayerReady&&(this.isPlayerReady=!0,!0)}goRequest(){return!this.isRequested&&(this.isRequested=!0,this.timeSinceLastAd.reset(),this.timeSinceRequested.start(),!0)}goStart(){return!(!this.isRequested||this.isStarted)&&(this.isAd()?this.numberOfAds++:this.numberOfVideos++,this.isStarted=!0,this.isPlaying=!0,this.timeSinceStarted.start(),this.playtimeSinceLastEvent.start(),!0)}goEnd(){return!!this.isRequested&&(this.numberOfErrors=0,this.resetFlags(),this.timeSinceRequested.stop(),this.timeSinceStarted.stop(),this.playtimeSinceLastEvent.stop(),this.isPlaying=!1,!0)}goPause(){return!(!this.isStarted||this.isPaused)&&(this.isPaused=!0,this.isPlaying=!1,this.timeSincePaused.start(),this.playtimeSinceLastEvent.stop(),this.timeSinceResumed.reset(),this.isBuffering&&(this._bufferAcc+=this.bufferElapsedTime.getDeltaTime()),this.elapsedTime.start(),!0)}goResume(){return!(!this.isStarted||!this.isPaused)&&(this.isPaused=!1,this.isPlaying=!0,this.timeSincePaused.stop(),this.timeSinceResumed.start(),this._hb?(this._acc=this.elapsedTime.getDeltaTime(),this._hb=!1):(this.isBuffering&&this.bufferElapsedTime.start(),this._acc+=this.elapsedTime.getDeltaTime()),!0)}goBufferStart(){return!(!this.isRequested||this.isBuffering)&&(this.isBuffering=!0,this.isPlaying=!1,this.timeSinceBufferBegin.start(),this.bufferElapsedTime.start(),!0)}goBufferEnd(){return!(!this.isRequested||!this.isBuffering)&&(this.isBuffering=!1,this.isPlaying=!0,this.timeSinceBufferBegin.stop(),this._hb?(this._bufferAcc=this.bufferElapsedTime.getDeltaTime(),this._hb=!1):this._bufferAcc+=this.bufferElapsedTime.getDeltaTime(),!this.isAd()&&this.initialBufferingHappened&&(this.totalRebufferingTime+=this.timeSinceBufferBegin.stopTime-this.timeSinceBufferBegin.startTime),!0)}goSeekStart(){return!(!this.isStarted||this.isSeeking)&&(this.isSeeking=!0,this.isPlaying=!1,this.timeSinceSeekBegin.start(),this.timeSinceSeekEnd.reset(),!0)}goSeekEnd(){return!(!this.isStarted||!this.isSeeking)&&(this.isSeeking=!1,this.isPlaying=!0,this.timeSinceSeekBegin.stop(),this.timeSinceSeekEnd.start(),!0)}goAdBreakStart(){return!this.isAdBreak&&(this.isAdBreak=!0,this.timeSinceAdBreakStart.start(),!0)}goAdBreakEnd(){return!!this.isAdBreak&&(this.isRequested=!1,this.isAdBreak=!1,this.totalAdPlaytime=this.timeSinceAdBreakStart.getDeltaTime(),this.timeSinceAdBreakStart.stop(),!0)}goDownload(){this.timeSinceLastDownload.start()}goHeartbeat(){this.timeSinceLastHeartbeat.start()}goRenditionChange(){this.timeSinceLastRenditionChange.start()}goAdQuartile(){this.timeSinceLastAdQuartile.start()}goError(){this.isError=!0,this.numberOfErrors++,this.isAd()?this.timeSinceLastAdError.start():(this.timeSinceLastError.start(),this.isStarted?this.hadPlaybackError=!0:this.hadStartupError=!0)}goLastAd(){this.timeSinceLastAd.start()}trackContentBitrateState(e){if(e&&"number"==typeof e){this.peakBitrate=Math.max(this.peakBitrate,e);const t=Date.now();if(!this.isPlaying){if(null!==this._lastBitrate&&null!==this._lastBitrateChangeTimestamp){const e=t-this._lastBitrateChangeTimestamp;e>0&&(this.partialAverageBitrate+=this._lastBitrate*e,this._totalBitrateDuration+=e),this._lastBitrateChangeTimestamp=null}return void(this._lastBitrate=e)}if(null===this._lastBitrateChangeTimestamp&&null!==this._lastBitrate&&(this._lastBitrateChangeTimestamp=t),null!==this._lastBitrate&&this._lastBitrate!==e&&null!==this._lastBitrateChangeTimestamp){const e=t-this._lastBitrateChangeTimestamp;e>0&&(this.partialAverageBitrate+=this._lastBitrate*e,this._totalBitrateDuration+=e),this._lastBitrateChangeTimestamp=t}null===this._lastBitrateChangeTimestamp&&(this._lastBitrateChangeTimestamp=t),this._lastBitrate=e;let i=this.partialAverageBitrate,s=this._totalBitrateDuration;const r=t-this._lastBitrateChangeTimestamp;r>0&&(i+=e*r,s+=r),this.weightedBitrate=s>0?Math.round(i/s):e}}trackDownloadRate(e){!e||"number"!=typeof e||e<=0||e!==this._lastDownloadBitrate&&(this._downloadBitrates.push(e),this._lastDownloadBitrate=e)}addPlayedRendition(e,t){e&&t&&this._playedRenditions.add(`${e}x${t}`)}resetViewIdTrackedState(){this.peakBitrate=0,this.startupTime=null,this.partialAverageBitrate=0,this._totalBitrateDuration=0,this.weightedBitrate=0,this._lastBitrate=null,this._lastBitrateChangeTimestamp=null,this._downloadBitrates=[],this._lastDownloadBitrate=null,this.totalSwitchUps=0,this.totalSwitchDowns=0,this.timeSincePaused.reset(),this._playedRenditions=new Set}clearTotalAdsTime(){n.debug("clear total ads time",this.totalAdTime),this._totalAdPlaytime.reset()}totalAdTime(){return this._totalAdPlaytime.getDuration()}startAdsTime(){return n.debug("startAdsTime"),this._totalAdPlaytime.start()}stopAdsTime(){return n.debug("stopAdsTime"),this._totalAdPlaytime.stop()}setStartupTime(e){null===this.startupTime&&(this.startupTime=Math.max(this.timeSinceRequested.getDeltaTime()-e,0))}};class P extends f{static Events;state;adsTracker;_lastBufferType;_userId;_src;player;tag;_lastWebkitBitrate;_lastAdRendition;_lastRendition;constructor(e,t){super(),this.state=new I,this.adsTracker=null,this._lastBufferType=null,this._userId=null,this._src=null,t=t||{},this.setOptions(t),e&&this.setPlayer(e,t.tag),n.notice("Tracker "+this.getTrackerName()+" v"+this.getTrackerVersion()+" is ready.")}setUserId(e){this._userId=e}setOptions(e){e&&(e.adsTracker&&this.setAdsTracker(e.adsTracker),"boolean"==typeof e.isAd&&this.setIsAd(e.isAd),void 0!==e.src&&(null!==this._src&&this._src!==e.src?n.warn(`setOptions: src is locked to '${this._src}'. Ignoring override '${e.src}'.`):(this._src=e.src,this.adsTracker&&null==this.adsTracker._src&&(this.adsTracker._src=this._src))),f.prototype.setOptions.apply(this,arguments))}setPlayer(e,t){(this.player||this.tag)&&this.dispose(),"undefined"!=typeof document&&document.getElementById&&("string"==typeof e&&(e=document.getElementById(e)),"string"==typeof t&&(t=document.getElementById(t))),t=t||e,this.player=e,this.tag=t,this.registerListeners()}isAd(){return this.state.isAd()}setIsAd(e){this.state.setIsAd(e)}setAdsTracker(e){this.disposeAdsTracker(),e&&(this.adsTracker=e,this.adsTracker.setIsAd(!0),this.adsTracker.parentTracker=this,null!=this._src&&null==e._src&&(e._src=this._src),this.adsTracker.on("*",O.bind(this)))}disposeAdsTracker(){this.adsTracker&&(this.adsTracker.off("*",O),this.adsTracker.dispose())}dispose(){this.stopHeartbeat(),this.disposeAdsTracker(),this.unregisterListeners(),this.player=null,this.tag=null}registerListeners(){}unregisterListeners(){}getViewId(){return this.parentTracker?this.parentTracker.getViewId():this.state.getViewId()}getViewSession(){return this.parentTracker?this.parentTracker.getViewSession():this.state.getViewSession()}getVideoId(){return null}getTitle(){return null}isLive(){return null}getBitrate(){return null}getManifestBitrate(){return null}getSegmentDownloadBitrate(){return null}getNetworkDownloadBitrate(){return null}getWebkitBitrate(){if(this.tag&&this.tag.webkitVideoDecodedByteCount){let e;if(this._lastWebkitBitrate){e=this.tag.webkitVideoDecodedByteCount;let t=e-this._lastWebkitBitrate,i=this.getHeartbeat()/1e3;e=Math.round(t/i*8)}return this._lastWebkitBitrate=this.tag.webkitVideoDecodedByteCount,e||null}}getRenditionName(){return null}getRenditionBitrate(){return null}getRenditionShift(e){let t,i=this.getManifestBitrate();return this.isAd()?(t=this._lastAdRendition,e&&(this._lastAdRendition=i)):(t=this._lastRendition,e&&(this._lastRendition=i)),i&&t?i>t?"up":i<t?"down":null:null}getRenditionHeight(){return this.tag?this.tag.videoHeight:null}getRenditionWidth(){return this.tag?this.tag.videoWidth:null}getDuration(){return this.tag?this.tag.duration:null}getPlayhead(){return this.tag?this.tag.currentTime:null}getLanguage(){return null}getSrc(){return this.tag?this.tag.currentSrc:null}getPlayrate(){return this.tag?this.tag.playbackRate:null}isMuted(){return this.tag?this.tag.muted:null}isFullscreen(){return null}getCdn(){return null}getPlayerName(){return this.getTrackerName()}getPlayerVersion(){return l}getFps(){return null}isAutoplayed(){return this.tag?this.tag.autoplay:null}getPreload(){return this.tag?this.tag.preload:null}getAdQuartile(){return null}getAdPosition(){return this.parentTracker?this.parentTracker.state.isStarted?"mid":"pre":null}getAdPartner(){return null}getAdCreativeId(){return null}getInstrumentationProvider(){return null}getInstrumentationName(){return null}getInstrumentationVersion(){return null}getAttributes(e,t){if(void 0===(e=f.prototype.getAttributes.apply(this,arguments)).isAd&&(e.isAd=this.isAd()),e.viewSession=this.getViewSession(),e.viewId=this.getViewId(),e.playerName=this.getPlayerName(),e.playerVersion=this.getPlayerVersion(),e["instrumentation.provider"]=this.getInstrumentationProvider(),e["instrumentation.name"]=this.getInstrumentationName(),e["instrumentation.version"]=this.getInstrumentationVersion(),e["enduser.id"]=this._userId,e.src=this._src||"Browser","customAction"===t)return e;try{e.pageUrl=window.location.href}catch(e){}this.isAd()?(e.adId=this.getVideoId(),e.adTitle=this.getTitle(),e.adSrc=this.getSrc(),e.adCdn=this.getCdn(),this.state.isStarted&&(e.adBitrate=this.getBitrate()||0),e.adRenditionName=this.getRenditionName(),e.adRenditionHeight=this.getRenditionHeight(),e.adRenditionWidth=this.getRenditionWidth(),e.adDuration=this.getDuration(),e.adPlayhead=this.getPlayhead(),e.adLanguage=this.getLanguage(),e.adIsMuted=this.isMuted(),e.adFps=this.getFps(),e.adPosition=this.getAdPosition(),e.adCreativeId=this.getAdCreativeId(),e.adPartner=this.getAdPartner()):(e.contentId=this.getVideoId(),e.contentTitle=this.getTitle(),e.contentSrc=this.getSrc(),e.contentCdn=this.getCdn(),e.contentPlayhead=this.getPlayhead(),e.contentIsLive=this.isLive(),this.state.isStarted&&(e.contentBitrate=this.getBitrate()||0,e.contentManifestBitrate=this.getManifestBitrate()||0,e.contentSegmentDownloadBitrate=this.getSegmentDownloadBitrate()||0,e.contentNetworkDownloadBitrate=this.getNetworkDownloadBitrate()||0),e.contentRenditionName=this.getRenditionName(),e.contentRenditionHeight=this.getRenditionHeight(),e.contentRenditionWidth=this.getRenditionWidth(),e.contentDuration=this.getDuration(),e.contentLanguage=this.getLanguage(),e.contentPlayrate=this.getPlayrate(),e.contentIsFullscreen=this.isFullscreen(),e.contentIsMuted=this.isMuted(),e.contentIsAutoplayed=this.isAutoplayed(),e.contentPreload=this.getPreload(),e.contentFps=this.getFps(),null!=this.adsTracker&&this.adsTracker.state.totalAdPlaytime>0&&(e.totalAdPlaytime=this.adsTracker.state.totalAdPlaytime)),this.state.getStateAttributes(e),this.state.isStarted&&!this.isAd()&&(this.state.trackContentBitrateState(e.contentBitrate),this.state.trackDownloadRate(e.contentNetworkDownloadBitrate),this.state.addPlayedRendition(e.contentRenditionHeight,e.contentRenditionWidth));for(let t in this.customData)e[t]=this.customData[t];if(!this.isAd()){this.state.getQoeAttributes(e);const t=e.qoe;for(let e in this.customData)t[e]=this.customData[e]}return e}sendCustom(e,t,i){i=i||{},this.sendVideoCustomAction(e,i),this.state.setTimeSinceAttribute(t)}sendPlayerReady(e){this.state.goPlayerReady()&&(e=e||{},this.sendVideoAction(P.Events.PLAYER_READY,e))}sendRequest(e){if(this.state.goRequest()){let t;this.isAd()?(t=P.Events.AD_REQUEST,this.sendVideoAdAction(t,e)):(t=P.Events.CONTENT_REQUEST,this.sendVideoAction(t,e))}}sendStart(e){if(this.state.goStart()){let t;if(this.isAd())t=P.Events.AD_START,this.parentTracker&&(this.parentTracker.state.isPlaying=!1),this.sendVideoAdAction(t,e),this.state.startAdsTime();else{t=P.Events.CONTENT_START;let i=0;this.adsTracker&&((this.adsTracker.state.isPlaying||this.adsTracker.state.isBuffering)&&(this.adsTracker.state.stopAdsTime(),this.adsTracker.state.isPlaying=!1,this.adsTracker.state.isBuffering=!1),i=this.adsTracker.state.totalAdTime()??0),this.state.setStartupTime(i),this.sendVideoAction(t,e);const s=this.getHarvester?.();s?.setBeforeDrainCallback(()=>{if(this.state){const e=this.state.getQoeAttributes({}).qoe;s.refreshQoeKpis(e,this.getViewId())}})}this.startHeartbeat(),this.state.goHeartbeat()}}sendEnd(e){if(this.state.goEnd()){let t;if(e=e||{},this.isAd()?(t=P.Events.AD_END,e.timeSinceAdRequested=this.state.timeSinceRequested.getDeltaTime(),e.timeSinceAdStarted=this.state.timeSinceStarted.getDeltaTime(),this.parentTracker&&(this.parentTracker.state.isPlaying=!0,this.parentTracker.state.timeSincePaused.reset()),this.state.stopAdsTime()):(t=P.Events.CONTENT_END,e.timeSinceRequested=this.state.timeSinceRequested.getDeltaTime(),e.timeSinceStarted=this.state.timeSinceStarted.getDeltaTime()),this.stopHeartbeat(),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e),this.parentTracker&&this.isAd()&&this.parentTracker.state.goLastAd(),this.state.goViewCountUp(),this.state.totalPlaytime=0,!this.isAd()){const e=this.getHarvester?.();e?.forceNextQoeCycle?.(),e?.setBeforeDrainCallback(null),this.adsTracker&&this.adsTracker.state.clearTotalAdsTime(),this.state.resetViewIdTrackedState()}}}sendPause(e){if(this.state.goPause()){let t=this.isAd()?P.Events.AD_PAUSE:P.Events.CONTENT_PAUSE;this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendResume(e){if(this.state.goResume()){let t;e=e||{},this.isAd()?(t=P.Events.AD_RESUME,e.timeSinceAdPaused=this.state.timeSincePaused.getDeltaTime()):(t=P.Events.CONTENT_RESUME,e.timeSincePaused=this.state.timeSincePaused.getDeltaTime()),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendBufferStart(e){if(this.state.goBufferStart()){let t;e=e||{},t=this.isAd()?P.Events.AD_BUFFER_START:P.Events.CONTENT_BUFFER_START,e=this.buildBufferAttributes(e),this._lastBufferType=e.bufferType,this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendBufferEnd(e){if(this.state.goBufferEnd()){let t;e=e||{},this.isAd()?(t=P.Events.AD_BUFFER_END,e.timeSinceAdBufferBegin=this.state.timeSinceBufferBegin.getDeltaTime()):(t=P.Events.CONTENT_BUFFER_END,e.timeSinceBufferBegin=this.state.timeSinceBufferBegin.getDeltaTime()),e=this.buildBufferAttributes(e),null!=this._lastBufferType&&(e.bufferType=this._lastBufferType),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e),this.state.initialBufferingHappened=!0}}buildBufferAttributes(e){return null==e.timeSinceStarted||e.timeSinceStarted<100?e.isInitialBuffering=!this.state.initialBufferingHappened:e.isInitialBuffering=!1,e.bufferType=this.state.calculateBufferType(e.isInitialBuffering),e.timeSinceResumed=this.state.timeSinceResumed.getDeltaTime(),e.timeSinceSeekEnd=this.state.timeSinceSeekEnd.getDeltaTime(),e}sendSeekStart(e){if(this.state.goSeekStart()){let t;t=this.isAd()?P.Events.AD_SEEK_START:P.Events.CONTENT_SEEK_START,this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendSeekEnd(e){if(this.state.goSeekEnd()){let t;e=e||{},this.isAd()?(t=P.Events.AD_SEEK_END,e.timeSinceAdSeekBegin=this.state.timeSinceSeekBegin.getDeltaTime()):(t=P.Events.CONTENT_SEEK_END,e.timeSinceSeekBegin=this.state.timeSinceSeekBegin.getDeltaTime()),this.isAd()?this.sendVideoAdAction(t,e):this.sendVideoAction(t,e)}}sendDownload(e){(e=e||{}).state||n.warn("Called sendDownload without { state: xxxxx }."),this.sendVideoAction(P.Events.DOWNLOAD,e),this.state.goDownload()}sendError(e){(e=e||{}).isAd=this.isAd(),this.state.goError();let t=this.isAd()?P.Events.AD_ERROR:P.Events.CONTENT_ERROR;this.sendVideoErrorAction(t,e)}sendRenditionChanged(e){(e=e||{}).timeSinceLastRenditionChange=this.state.timeSinceLastRenditionChange.getDeltaTime();const{oldBitrate:t,newBitrate:i}=e;let s;this.isAd()||void 0===t||void 0===i||(i>t?(e.shift="up",this.state.totalSwitchUps+=1):i<t?(e.shift="down",this.state.totalSwitchDowns+=1):e.shift=null),delete e.oldBitrate,delete e.newBitrate,s=this.isAd()?P.Events.AD_RENDITION_CHANGE:P.Events.CONTENT_RENDITION_CHANGE,this.isAd()?this.sendVideoAdAction(s,e):this.sendVideoAction(s,e),this.state.goRenditionChange()}sendHeartbeat(e){if(this.state.isRequested){let t,i=this.getHeartbeat();this.state._hb=!0,i=this.adjustElapsedTimeForPause(i),this.isAd()?(t=P.Events.AD_HEARTBEAT,"bitmovin-ads"===this.getPlayerName()?this.sendVideoAdAction(t,e):this.sendVideoAdAction(t,{elapsedTime:i,...e})):(t=P.Events.CONTENT_HEARTBEAT,this.sendVideoAction(t,{elapsedTime:i,...e})),this.state.goHeartbeat()}}adjustElapsedTimeForPause(e){return this.state._acc&&(e-=this.state._acc,this.state._acc=0),this.state.isPaused&&((e-=this.state.elapsedTime.getDeltaTime())<10&&(e=0),this.state.elapsedTime.start()),this.state._bufferAcc?(e-=this.state._bufferAcc,this.state._bufferAcc=0):this.state.isBuffering&&((e-=this.state.bufferElapsedTime.getDeltaTime())<5&&(e=0),this.state.bufferElapsedTime.start()),Math.max(0,e)}sendAdBreakStart(e){this.isAd()&&this.state.goAdBreakStart()&&(this.state.totalAdPlaytime=0,this.parentTracker&&(this.parentTracker.state.isPlaying=!1),this.sendVideoAdAction(P.Events.AD_BREAK_START,e))}sendAdBreakEnd(e){this.isAd()&&this.state.goAdBreakEnd()&&((e=e||{}).timeSinceAdBreakBegin=this.state.timeSinceAdBreakStart.getDeltaTime(),this.sendVideoAdAction(P.Events.AD_BREAK_END,e),this.parentTracker&&(this.parentTracker.state.isPlaying=!0),this.stopHeartbeat(),this.parentTracker&&this.isAd()&&this.parentTracker.state.goLastAd())}sendAdQuartile(e){this.isAd()&&((e=e||{}).quartile||n.warn("Called sendAdQuartile without { quartile: xxxxx }."),e.timeSinceLastAdQuartile=this.state.timeSinceLastAdQuartile.getDeltaTime(),this.sendVideoAdAction(P.Events.AD_QUARTILE,e),this.state.goAdQuartile())}sendAdClick(e){this.isAd()&&((e=e||{}).url||n.warn("Called sendAdClick without { url: xxxxx }."),this.sendVideoAdAction(P.Events.AD_CLICK,e))}}function O(e){e.type!==P.Events.AD_ERROR?this.sendVideoAdAction(e.type,e.data):this.sendVideoErrorAction(e.type,e.data)}P.Events={PLAYER_READY:"PLAYER_READY",DOWNLOAD:"DOWNLOAD",ERROR:"ERROR",CONTENT_REQUEST:"CONTENT_REQUEST",CONTENT_START:"CONTENT_START",CONTENT_END:"CONTENT_END",CONTENT_PAUSE:"CONTENT_PAUSE",CONTENT_RESUME:"CONTENT_RESUME",CONTENT_SEEK_START:"CONTENT_SEEK_START",CONTENT_SEEK_END:"CONTENT_SEEK_END",CONTENT_BUFFER_START:"CONTENT_BUFFER_START",CONTENT_BUFFER_END:"CONTENT_BUFFER_END",CONTENT_HEARTBEAT:"CONTENT_HEARTBEAT",CONTENT_RENDITION_CHANGE:"CONTENT_RENDITION_CHANGE",CONTENT_ERROR:"CONTENT_ERROR",AD_REQUEST:"AD_REQUEST",AD_START:"AD_START",AD_END:"AD_END",AD_PAUSE:"AD_PAUSE",AD_RESUME:"AD_RESUME",AD_SEEK_START:"AD_SEEK_START",AD_SEEK_END:"AD_SEEK_END",AD_BUFFER_START:"AD_BUFFER_START",AD_BUFFER_END:"AD_BUFFER_END",AD_HEARTBEAT:"AD_HEARTBEAT",AD_RENDITION_CHANGE:"AD_RENDITION_CHANGE",AD_ERROR:"AD_ERROR",AD_BREAK_START:"AD_BREAK_START",AD_BREAK_END:"AD_BREAK_END",AD_QUARTILE:"AD_QUARTILE",AD_CLICK:"AD_CLICK"};const H=P,{MAX_PAYLOAD_SIZE:V,MAX_EVENTS_PER_BATCH:L}=o;class Q{buffer;maxPayloadSize;maxEventsPerBatch;currentPayloadSize;totalEvents;smartHarvestPayloadThreshold;overflowPayloadThreshold;smartHarvestEventThreshold;overflowEventThreshold;onSmartHarvestTrigger;constructor(){this.buffer=[],this.maxPayloadSize=V,this.maxEventsPerBatch=L,this.currentPayloadSize=0,this.totalEvents=0,this.smartHarvestPayloadThreshold=Math.floor(.6*this.maxPayloadSize),this.overflowPayloadThreshold=Math.floor(.9*this.maxPayloadSize),this.smartHarvestEventThreshold=Math.floor(.6*this.maxEventsPerBatch),this.overflowEventThreshold=Math.floor(.9*this.maxEventsPerBatch),this.onSmartHarvestTrigger=null}addOrReplaceByActionName(e,t){const i=this.buffer.findIndex(t=>t.actionName===e);try{return-1===i?this.add(t):this.add(t,i),!0}catch(e){return n.error("Failed to set or replace the event to buffer:",e.message),!1}}addOrReplaceByActionNameAndViewId(e,t,i){const s=this.buffer.findIndex(i=>i.actionName===e&&i.viewId===t);try{return-1===s?this.add(i):this.add(i,s),!0}catch(e){return n.error("Failed to set or replace the event to buffer:",e.message),!1}}findByActionNameAndViewId(e,t){return this.buffer.find(i=>i.actionName===e&&i.viewId===t)||null}findByActionName(e){return this.buffer.find(t=>t.actionName===e)||null}add(e,t){try{const i=m(e)??0,s=this.currentPayloadSize+i>=this.maxPayloadSize,r=this.totalEvents+1>=this.maxEventsPerBatch;if((s||r)&&this.makeRoom(i),null!=t&&t>-1){const s=m(this.buffer[t])??0;this.buffer[t]=e,this.currentPayloadSize+=i-s}else this.buffer.push(e),this.totalEvents++,this.currentPayloadSize+=i;return this.checkSmartHarvestTrigger(),!0}catch(e){return n.error("Failed to add event to buffer:",e.message),!1}}checkSmartHarvestTrigger(){const e=this.currentPayloadSize/this.maxPayloadSize,t=this.totalEvents/this.maxEventsPerBatch,i=this.currentPayloadSize>=this.overflowPayloadThreshold,s=this.totalEvents>=this.overflowEventThreshold;if(i||s){const s=i?`payload ${this.currentPayloadSize}/${this.maxPayloadSize} bytes (${Math.round(100*e)}%)`:`events ${this.totalEvents}/${this.maxEventsPerBatch} (${Math.round(100*t)}%)`;n.warn(`OVERFLOW PREVENTION: ${s} - Emergency harvest triggered`),this.onSmartHarvestTrigger&&"function"==typeof this.onSmartHarvestTrigger&&this.onSmartHarvestTrigger("overflow",90)}else{const e=this.currentPayloadSize>=this.smartHarvestPayloadThreshold,t=this.totalEvents>=this.smartHarvestEventThreshold;(e||t)&&this.onSmartHarvestTrigger&&"function"==typeof this.onSmartHarvestTrigger&&this.onSmartHarvestTrigger("smart",60)}}setSmartHarvestCallback(e){this.onSmartHarvestTrigger=e}drain(){try{const e=this.buffer.splice(0);return this.totalEvents=0,this.currentPayloadSize=0,e}catch(e){return n.error("Failed to drain events from buffer:",e.message),[]}}isEmpty(){return 0===this.totalEvents}size(){return this.totalEvents}clear(){this.buffer=[],this.totalEvents=0}makeRoom(e){if(e>this.maxPayloadSize)n.error("Event dropped: Event size exceeds maximum payload size.");else for(;(this.totalEvents>=this.maxEventsPerBatch||this.currentPayloadSize+e>=this.maxPayloadSize)&&this.buffer.length>0;){const e=m(this.buffer.shift())??0;this.totalEvents--,this.currentPayloadSize-=e,n.warn("Event buffer full, oldest event removed.")}}}const{MAX_PAYLOAD_SIZE:x,MAX_EVENTS_PER_BATCH:F}=o;class q{retryQueue;maxQueueSize;maxQueueSizeBytes;constructor(){this.retryQueue=[],this.maxQueueSize=F,this.maxQueueSizeBytes=x}addFailedEvents(e){try{const t=Array.isArray(e)?e:[e];n.notice(`Adding ${t.length} failed events to retry queue`,{queueSizeBefore:this.retryQueue.length});for(const e of t){this.retryQueue.length>=this.maxQueueSize&&this.evictOldestEvent();const t=m(e)??0;for(;(m(this.retryQueue)??0)+t>this.maxQueueSizeBytes;)this.evictOldestEvent();this.retryQueue.push({...e})}}catch(e){n.error("Failed to add events to retry queue:",e.message)}}discardEvent(e,t){n.warn("Discarded event",{reason:t,eventType:e.eventType})}evictOldestEvent(){if(this.retryQueue.length>0){const e=this.retryQueue.shift();this.discardEvent(e,"Queue full - evicted oldest")}}getRetryEventsToFit(e,t){const i=[];let s=0,r=0;for(let a=this.retryQueue.length-1;a>=0;a--){const n=this.retryQueue[a];if(r>=t)break;const o=m(n)??0;if(s+o>e)break;i.unshift(n),s+=o,r++,this.retryQueue.splice(a,1)}return i}getQueueSize(){return this.retryQueue.length}clear(){this.retryQueue=[]}}function z(e,t){return t&&0!==t.length?t.reduce((e,t)=>{let i;try{if(t.regex instanceof RegExp){const e=t.regex.flags.includes("g")?t.regex.flags:t.regex.flags+"g";i=new RegExp(t.regex.source,e)}else i=new RegExp(t.regex,"g")}catch(i){return n.warn("applyObfuscationRules: invalid regex, skipping rule:",t.regex,i.message),e}return e.replace(i,t.replacement)},e):e}class U{async send(e,t){const{url:i,payload:s,options:r={}}=e;try{if(!i||!s)throw new Error("URL and payload are required");const e={url:i,payload:s,options:r,callback:t};await this.executeRequest(e)}catch(e){n.error("Failed to send request:",e.message),t({retry:!1,status:0,error:e.message})}}async executeRequest(e){const{url:t,payload:i,options:s,callback:r}=e,a=Date.now();try{const r=z(JSON.stringify(i.body),window.NRVIDEO?.config?.obfuscate);if(s.isFinalHarvest&&navigator.sendBeacon){const i=await this.sendWithBeacon(t,r),s={success:i,status:i?204:0};return void this.handleRequestComplete(e,s,a)}const n=await this.fetchWithTimeout(t,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:s.isFinalHarvest},1e4),o={success:n.ok,status:n.status,statusText:n.statusText};this.handleRequestComplete(e,o,a)}catch(t){const i={success:!1,status:0,error:t.message};this.handleRequestComplete(e,i,a)}}handleRequestComplete(e,t,i){const{callback:s}=e;s({retry:!t.success&&(0===t.status||function(e){switch(e){case 408:case 429:case 500:return!0;case 401:case 403:case 404:return!1}return e>=502&&e<=504||e>=512&&e<=530}(t.status)),status:t.status,error:t.error})}async sendWithBeacon(e,t){try{return navigator.sendBeacon(e,t)}catch(e){return n.warn("sendBeacon failed, falling back to fetch:",e.message),!1}}async fetchWithTimeout(e,t,i){const s=new AbortController,r=setTimeout(()=>s.abort(),i);try{const i=await fetch(e,{...t,signal:s.signal});return clearTimeout(r),i}catch(e){if(clearTimeout(r),"AbortError"===e.name)throw new Error(`Request timeout after ${i}ms`);throw e}}}function M(e,t){return!!t&&(t.actionName===f.Events.QOE_AGGREGATE?t.viewId?e.addOrReplaceByActionNameAndViewId(f.Events.QOE_AGGREGATE,t.viewId,t):e.addOrReplaceByActionName(f.Events.QOE_AGGREGATE,t):e.add(t))}function G(e,t,i){if(!e||!t)return;const s=i?e.findByActionNameAndViewId(f.Events.QOE_AGGREGATE,i):e.findByActionName(f.Events.QOE_AGGREGATE);if(!s)return;const r={...s};for(const e of o.QOE_KPI_KEYS)e in t&&(r[e]=t[e]);i?e.addOrReplaceByActionNameAndViewId(f.Events.QOE_AGGREGATE,i,r):e.addOrReplaceByActionName(f.Events.QOE_AGGREGATE,r)}function K(e,t){const i=e[t.viewId];if(!i)return!1;for(const e of o.QOE_KPI_KEYS)if(t[e]!==i[e])return!1;return!0}function $(e,t){const i={};for(const e of o.QOE_KPI_KEYS)i[e]=t[e];e[t.viewId]=i}function j(e,t,i){if(t)return e;const s=[];for(const t of e)t.actionName===f.Events.QOE_AGGREGATE?i.add(t):s.push(t);return s}function W(e,t,i){for(let s=e.length-1;s>=0;s--){const r=e[s];r.actionName===f.Events.QOE_AGGREGATE&&(!i&&K(t,r)?e.splice(s,1):$(t,r))}}function Y({interval:e,onTick:t,errorLabel:i}){let s=!1,r=null,a=e;function o(){s&&(r=setTimeout(async()=>{r=null;try{await t()}catch(e){n.error(`${i}: scheduled tick failed:`,e.message)}finally{s&&o()}},a))}return{start(){s||(s=!0,o())},stop(){s=!1,r&&(clearTimeout(r),r=null)},cancelAndReschedule(){r&&(clearTimeout(r),r=null),s&&o()},updateInterval(e){"number"!=typeof e||e<=0||(a=e,s&&r&&(clearTimeout(r),r=null,o()))},isRunning:()=>s}}class X{eventBuffer;retryQueueHandler;httpClient;fallBackUrl;retryCount;harvestCycle;isHarvesting;qoeCycleCount;forceNextQoeCycle;beforeDrainCallback;_lastSentQoeKpis;timer;constructor(e){this.eventBuffer=e,this.retryQueueHandler=new q,this.httpClient=new U,this.fallBackUrl="",this.retryCount=0,this.eventBuffer instanceof Q&&this.eventBuffer.setSmartHarvestCallback((e,t)=>this.triggerSmartHarvest(e,t)),this.harvestCycle=o.INTERVAL,this.isHarvesting=!1,this.qoeCycleCount=1,this.forceNextQoeCycle=!1,this.beforeDrainCallback=null,this._lastSentQoeKpis={},this.timer=Y({interval:this.harvestCycle,onTick:()=>this.onHarvestInterval(),errorLabel:"HarvestScheduler"}),this.setupPageLifecycleHandlers()}get isStarted(){return this.timer.isRunning()}startScheduler(){this.timer.isRunning()?n.warn("Harvest scheduler is already started"):(n.notice("Starting harvest scheduler",{harvestCycle:this.harvestCycle,eventBufferSize:this.eventBuffer?this.eventBuffer.size():0}),this.timer.start())}stopScheduler(){this.timer.isRunning()&&(this.timer.stop(),n.notice("Harvest scheduler stopped"))}async triggerSmartHarvest(e,t){if(n.notice(`${e} harvest triggered at ${t}% threshold`,{type:e,threshold:t}),this.eventBuffer&&!this.eventBuffer.isEmpty())try{await this.triggerHarvest({})}catch(t){n.error(`${e} harvest failed:`,t.message)}finally{this.timer.cancelAndReschedule()}}async onHarvestInterval(){const e=this.eventBuffer&&!this.eventBuffer.isEmpty(),t=this.retryQueueHandler&&this.retryQueueHandler.getQueueSize()>0;(e||t)&&await this.triggerHarvest({})}async triggerHarvest(e={}){if(this.isHarvesting)return{success:!1,reason:"harvest_in_progress"};this.isHarvesting=!0;try{let t=this.drainEvents(e);if(e.isFinalHarvest){const e=o.MAX_BEACON_SIZE;(m(t)??0)>e&&(t=this.trimEventsToFit(t,e))}const i=await this.sendChunk(t,e,!0);return{success:i.success,totalChunks:1,results:[i]}}catch(e){return n.error("Harvest cycle failed:",e.message),this.handleHarvestFailure(e),{success:!1,error:e.message}}finally{this.isHarvesting=!1}}trimEventsToFit(e,t){if(0===e.length)return e;const i=[];let s=0;for(let r=e.length-1;r>=0;r--){const a=e[r],n=m({ins:[a,...i]})??0;n>t||(i.unshift(a),s=n)}const r=e.length-i.length;if(r>0){const a=e.slice(0,r);n.warn(`Discarded ${r} events to fit beacon size limit`,{originalCount:e.length,trimmedCount:i.length,finalSize:s,maxSize:t}),this.retryQueueHandler&&this.retryQueueHandler.addFailedEvents(a)}return i}drainEvents(e={}){const t=window.NRVIDEO?.config?.qoeIntervalFactor??1,i=!!e.isFinalHarvest||this.forceNextQoeCycle,s=(this.qoeCycleCount-1)%t==0||i;if(this.forceNextQoeCycle&&(this.forceNextQoeCycle=!1),this.beforeDrainCallback&&"function"==typeof this.beforeDrainCallback)try{this.beforeDrainCallback()}catch(e){n.error("Before drain callback failed:",e.message)}let r=j(this.eventBuffer.drain(),s,this.eventBuffer);this.qoeCycleCount++,W(r,this._lastSentQoeKpis,i);let a=[...r],l=m(r)??0;if(this.retryQueueHandler&&this.retryQueueHandler.getQueueSize()>0){const e=o.MAX_PAYLOAD_SIZE-l,t=o.MAX_EVENTS_PER_BATCH-a.length;if(e>0&&t>0){const i=this.retryQueueHandler.getRetryEventsToFit(e,t);i.length>0&&(a=[...i,...a])}}return a}async sendChunk(e,t,i){const s={url:function(e){try{if(!window.NRVIDEO||!window.NRVIDEO.info)throw new Error("NRVIDEO info is not available.");let{beacon:t,licenseKey:i,applicationID:s}=window.NRVIDEO.info;if(!t||!i)throw new Error("Options object provided by New Relic is not correctly initialized");return s?`https://${e||t}/ins/1/${i}?a=${s}&v=${l}&ref=${window.location.href}&ca=VA`:`https://${e||t}/ins/1/${i}?&v=${l}&ref=${window.location.href}&ca=VA`}catch(e){return console.error(e.message),null}}(this.fallBackUrl),payload:{body:{ins:e}},options:{...t,isLastChunk:i}};return new Promise(t=>{this.httpClient.send(s,i=>{i.retry?this.handleRequestFailure(e):(this.retryCount=0,this.fallBackUrl=""),t({success:!i.retry,status:i.status,error:i.error,chunk:e,eventCount:e.length})})})}handleRequestFailure(e){this.retryQueueHandler.addFailedEvents(e),"US"===window.NRVIDEO?.info?.region&&(this.retryCount++,this.retryCount>5?(this.retryCount=0,this.fallBackUrl=""):this.retryCount>=2&&(this.fallBackUrl=o.COLLECTOR.US[1]))}handleHarvestFailure(e){n.warn("Harvest failure handled",{error:e.message})}updateHarvestInterval(e){"number"!=typeof e||isNaN(e)?n.warn("Invalid newInterval provided to updateHarvestInterval"):e<1e3||e>3e5?n.warn("newInterval out of bounds (1000-300000), ignoring"):this.harvestCycle!==e&&(this.harvestCycle=e,n.notice("Updated harvestCycle:",this.harvestCycle),this.timer.updateInterval(e))}setupPageLifecycleHandlers(){let e=!1;const t=()=>{e||(e=!0,this.triggerHarvest({isFinalHarvest:!0,force:!0}))};document.addEventListener("visibilitychange",()=>{document.hidden&&t()}),window.addEventListener("pagehide",()=>{t()}),window.addEventListener("beforeunload",()=>{t()})}}const Z=new class{isInitialized;harvestScheduler;eventBuffer;constructor(){this.isInitialized=!1,this.harvestScheduler=null,this.eventBuffer=null}initialize(){if(this.isInitialized)n.warn("Video analytics agent already initialized");else try{this.eventBuffer=new Q,this.harvestScheduler=new X(this.eventBuffer),this.harvestScheduler.startScheduler(),this.isInitialized=!0,n.notice("Video analytics agent initialized successfully")}catch(e){n.error("Failed to initialize video analytics agent:",e.message)}}addEvent(e){this.isInitialized||(n.warn("Video analytics agent not initialized, initializing now"),this.initialize());try{return M(this.eventBuffer,e)}catch(e){return n.error("Failed to add event to harvesting system:",e.message),!1}}setHarvestInterval(e){this.isInitialized||this.initialize(),this.harvestScheduler.updateHarvestInterval(e)}forceNextQoeCycle(){this.harvestScheduler&&(this.harvestScheduler.forceNextQoeCycle=!0)}setBeforeDrainCallback(e){this.harvestScheduler&&(this.harvestScheduler.beforeDrainCallback=e)}refreshQoeKpis(e,t){G(this.eventBuffer,e,t)}};E("Browser",Z);const J=Z;class ee{accountId;applicationToken;endpoint;harvestInterval;maxBufferSize;deviceInfo;eventBuffer;dataToken;isHarvesting;isDisposed;_isFetchingToken;timer;qoeCycleCount;forceQoeNextCycle;beforeDrainCallback;_lastSentQoeKpis;_connectAttempt;constructor({accountId:e,applicationToken:t,endpoint:i,deviceInfo:s}={}){if(!t)throw new Error("applicationToken is required");const r=i?.toLowerCase();if(!(r in S))throw new Error("Invalid endpoint");this.accountId=e,this.applicationToken=t,this.endpoint=r,this.harvestInterval=6e4,this.maxBufferSize=100,s||n.warn("ConnectedDeviceHarvester: no deviceInfo provided — using placeholder defaults. Pass info.deviceInfo for accurate device data.");const{uuid:a,osVersion:o,deviceModel:l,deviceManufacturer:h,osBuild:d,appBuild:c,architecture:u}=s??{};this.deviceInfo={uuid:a||_[5],osVersion:o||_[1],deviceModel:l||_[2],deviceManufacturer:h||_[8],osBuild:d||B.osBuild,appBuild:c||B.appBuild,architecture:u||B.architecture},this.eventBuffer=new Q,this.eventBuffer.setSmartHarvestCallback((e,t)=>this.triggerSmartHarvest(e,t)),this.dataToken=null,this.isHarvesting=!1,this.isDisposed=!1,this._isFetchingToken=!1,this.timer=Y({interval:this.harvestInterval,onTick:()=>this.sendBufferedEvents(),errorLabel:"ConnectedDeviceHarvester"}),this.qoeCycleCount=1,this.forceQoeNextCycle=!1,this.beforeDrainCallback=null,this._lastSentQoeKpis={},this._connectAttempt=0,this.initialise()}getEndpointBaseUrl(){return S[this.endpoint]??S.us}async initialise(){await this.fetchDataTokens(),this.isDisposed||this.dataToken&&this.startHarvestInterval()}async fetchDataTokens(){if(!this._isFetchingToken){this._isFetchingToken=!0;try{for(let e=0;e<3;e++){if(this.isDisposed)return;const t=`${this.getEndpointBaseUrl()}/v5/connect`;try{n.notice(`ConnectedDeviceHarvester: POST ${t} (attempt ${e+1}/3)`);const i=await this._fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json","X-App-License-Key":this.applicationToken},body:JSON.stringify(y)},1e4);if(!i.ok){let e="";try{e=await i.text()}catch(e){}throw new Error(`HTTP ${i.status} body=${e}`)}const s=await i.json();if(!s||!s.data_token)throw new Error("Missing data_token in connect response");return this.dataToken=s.data_token,this._connectAttempt=e+1,void n.notice("ConnectedDeviceHarvester: dataToken acquired")}catch(t){if(this._connectAttempt=e+1,n.error(`ConnectedDeviceHarvester: /v5/connect failed (attempt ${this._connectAttempt}/3):`,t.message),e>=2)return void n.error("ConnectedDeviceHarvester: Max retries reached — dataToken stays null");await new Promise(e=>setTimeout(e,1e4))}}}finally{this._isFetchingToken=!1}}}startHarvestInterval(){this.isDisposed||this.timer.start()}async triggerSmartHarvest(e,t){if(n.notice(`ConnectedDeviceHarvester: smart-harvest trigger (${e} at ${t}%)`),this.eventBuffer&&!this.eventBuffer.isEmpty())try{await this.sendBufferedEvents()}catch(t){n.error(`${e} smart-harvest failed:`,t.message)}finally{this.timer.cancelAndReschedule()}}addEvent(e){try{return M(this.eventBuffer,e)}catch(e){return n.error("ConnectedDeviceHarvester.addEvent failed:",e.message),!1}}forceQoeNextHarvest(){this.forceQoeNextCycle=!0}setBeforeDrainCallback(e){"function"!=typeof e&&null!==e||(this.beforeDrainCallback=e)}refreshQoeKpis(e,t){G(this.eventBuffer,e,t)}setHarvestInterval(e){"number"!=typeof e||e<=0||(this.harvestInterval=e,this.timer.updateInterval(e))}async sendBufferedEvents(){if(this.isHarvesting)return;if(!this.dataToken)return;if(this.eventBuffer.isEmpty())return;if("function"==typeof this.beforeDrainCallback)try{this.beforeDrainCallback()}catch(e){n.error("ConnectedDeviceHarvester beforeDrainCallback failed:",e.message)}this.isHarvesting=!0;const e=this.eventBuffer.drain(),t=globalThis.__NRVIDEO_CD__?.config?.qoeIntervalFactor??1,i=this.forceQoeNextCycle,s=(this.qoeCycleCount-1)%t==0||i;this.forceQoeNextCycle&&(this.forceQoeNextCycle=!1);const r=j(e,s,this.eventBuffer);if(this.qoeCycleCount++,W(r,this._lastSentQoeKpis,i),0===r.length)return void(this.isHarvesting=!1);const a=`${this.getEndpointBaseUrl()}/v3/data`,o={"Content-Type":"application/json","X-App-License-Key":this.applicationToken},l=()=>z(JSON.stringify([this.dataToken,this._buildDeviceInfo(),0,[],[],[],[],[],this._buildMetadata(),r]),globalThis.__NRVIDEO_CD__?.config?.obfuscate);try{let e=await this._fetchWithTimeout(a,{method:"POST",headers:o,body:l()},3e4);if(401===e.status){n.notice("ConnectedDeviceHarvester: /v3/data returned 401 — re-queuing events and reconnecting"),this.dataToken=null,this._connectAttempt=0;for(const e of r)this.eventBuffer.add(e);return void this.initialise()}if(!e.ok)throw new Error(`HTTP ${e.status}`);n.notice(`ConnectedDeviceHarvester: sent ${r.length} events`)}catch(e){n.error("ConnectedDeviceHarvester: /v3/data send failed:",e.message);for(const e of r)this.eventBuffer.add(e)}finally{this.isHarvesting=!1}}_buildDeviceInfo(){const e=this.deviceInfo;return[_[0],e.osVersion,e.deviceModel,_[3],_[4],e.uuid,"","",e.deviceManufacturer,_[9]]}_buildMetadata(){const e=this.deviceInfo;return{...B,osBuild:e.osBuild,appBuild:e.appBuild,architecture:e.architecture}}_fetchWithTimeout(e,t,i){const s=new AbortController,r=setTimeout(()=>s.abort(),i);return fetch(e,{...t,signal:s.signal}).finally(()=>clearTimeout(r))}async dispose(){return this.isDisposed=!0,this.timer.stop(),this.sendBufferedEvents()}}const te=new class{isInitialized;harvester;constructor(){this.isInitialized=!1,this.harvester=null}initialize(){if(this.isInitialized)return;const e=globalThis.__NRVIDEO_CD__?.info;if(e)try{this.harvester=new ee(e),this.isInitialized=!0,n.notice("ConnectedDeviceAnalyticsAgent initialized")}catch(e){n.error("ConnectedDeviceAnalyticsAgent.initialize failed:",e.message)}else n.warn("ConnectedDeviceAnalyticsAgent.initialize: globalThis.__NRVIDEO_CD__.info is missing")}addEvent(e){return this.isInitialized||this.initialize(),!!this.isInitialized&&this.harvester.addEvent(e)}forceQoeNextHarvest(){this.harvester&&this.harvester.forceQoeNextHarvest()}forceNextQoeCycle(){this.forceQoeNextHarvest()}setBeforeDrainCallback(e){this.harvester&&this.harvester.setBeforeDrainCallback(e)}refreshQoeKpis(e,t){this.isInitialized||this.initialize(),this.harvester&&this.harvester.refreshQoeKpis(e,t)}setHarvestInterval(e){this.isInitialized||this.initialize(),this.harvester&&this.harvester.setHarvestInterval(e)}};E("Vega",te);const ie=te,se={Constants:o,Chrono:c,Log:n,Emitter:h,Tracker:f,VideoTracker:H,VideoTrackerState:I,Core:N,version:l,NrVideoEventAggregator:Q,RetryQueueHandler:q,OptimizedHttpClient:U,HarvestScheduler:X,recordEvent:p};module.exports=t})();
3
3
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @license Apache-2.0
3
- * @newrelic/video-core 5.0.2
3
+ * @newrelic/video-core 5.1.0
4
4
  * Copyright New Relic <http://newrelic.com/>
5
5
  * @author Jordi Aguilar
6
6
  */