stormcloud-video-player 0.8.23 → 0.8.25

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 (42) hide show
  1. package/dist/stormcloud-vp.min.js +1 -1
  2. package/lib/index.cjs +1187 -1109
  3. package/lib/index.cjs.map +1 -1
  4. package/lib/index.d.cts +3 -1
  5. package/lib/index.d.ts +3 -1
  6. package/lib/index.js +1028 -954
  7. package/lib/index.js.map +1 -1
  8. package/lib/player/AdBreakOrchestrator.cjs +419 -26
  9. package/lib/player/AdBreakOrchestrator.cjs.map +1 -1
  10. package/lib/player/AdBreakOrchestrator.d.cts +2 -1
  11. package/lib/player/AdConfigManager.cjs +90 -22
  12. package/lib/player/AdConfigManager.cjs.map +1 -1
  13. package/lib/player/AdConfigManager.d.cts +1 -1
  14. package/lib/player/AdPreloadPool.d.cts +1 -1
  15. package/lib/player/AdTimingService.d.cts +1 -1
  16. package/lib/player/HlsEngine.d.cts +1 -1
  17. package/lib/player/PlayerControls.d.cts +1 -1
  18. package/lib/player/Scte35CueManager.d.cts +1 -1
  19. package/lib/player/Scte35Parser.d.cts +1 -1
  20. package/lib/player/StormcloudVideoPlayer.cjs +1184 -1110
  21. package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
  22. package/lib/player/StormcloudVideoPlayer.d.cts +1 -1
  23. package/lib/player/playerTypes.d.cts +1 -1
  24. package/lib/players/HlsPlayer.cjs +1184 -1110
  25. package/lib/players/HlsPlayer.cjs.map +1 -1
  26. package/lib/players/HlsPlayer.d.cts +1 -1
  27. package/lib/players/index.cjs +1184 -1110
  28. package/lib/players/index.cjs.map +1 -1
  29. package/lib/sdk/hlsAdPlayer.d.cts +1 -1
  30. package/lib/{types-DNiBmPKK.d.cts → types-Bz4aRmzc.d.cts} +1 -0
  31. package/lib/ui/StormcloudVideoPlayer.cjs +1184 -1110
  32. package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
  33. package/lib/ui/StormcloudVideoPlayer.d.cts +1 -1
  34. package/lib/utils/ctvVastSignals.cjs.map +1 -1
  35. package/lib/utils/tracking.cjs +411 -20
  36. package/lib/utils/tracking.cjs.map +1 -1
  37. package/lib/utils/tracking.d.cts +3 -2
  38. package/lib/utils/vastEnvironmentSignals.cjs +37 -0
  39. package/lib/utils/vastEnvironmentSignals.cjs.map +1 -1
  40. package/lib/utils/vastEnvironmentSignals.d.cts +4 -1
  41. package/lib/utils/vastMacros.cjs.map +1 -1
  42. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/player/AdBreakOrchestrator.cjs","../../src/player/AdBreakOrchestrator.ts","../../src/utils/mqttConfig.ts","../../src/utils/mqttClient.ts","../../src/utils/tracking.ts","../../src/player/PlayerControls.ts"],"names":["desc","__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","to","from","except","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","AdBreakOrchestrator","DEFAULT_MQTT_CONFIG","username","password","mqttConfig","import_mqtt","LOG","AdBreakOrchestrator_exports","enabled","brokerAddress","brokerPort","wsPort","topicPrefix","qos","isMQTTEnabled","brokerUrl","buildPlayerTopic","licenseKey","channel","require","client","status","initMQTTClient","url","buildMQTTBrokerUrl","clientId","random","reconnectPeriod","connectTimeout","Math","toString","slice","mqtt","connect","keepalive","clean","queueQoSZero","console","warn","err","on","info","message","ensureMQTTClient","publishMQTT","topic","payload","cachedBrowserId","screen","window","navigator","ua","userAgent","platform","vendor","memory","deviceMemory","hardwareConcurrency","screenInfo","width","height","availWidth","availHeight","orientation","type","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","includes","webosMatch","match","tizenMatch","tvMatch","trim","test","maxTouchPoints","androidModelMatch","outerHeight","outerWidth","matchMedia","matches","standalone","angle","substring","domain","location","hostname","origin","path","pathname","language","languages","join","cookieEnabled","doNotTrack","referrer","document","visibilityState","getBrowserID","clientInfo","crypto","fingerprintString","encodedData","utf8","buffer","i","hashBuffer","hashHex","hash","char","fallbackHash","timestamp","JSON","stringify","subtle","digest","Uint8Array","TextEncoder","encode","unescape","encodeURIComponent","length","buildPlayerMetricEvent","context","flags","input_stream_type","ad_played_count","sendHeartbeat","charCodeAt","Array","map","b","padStart","abs","Date","now","padEnd","canPublish","Boolean","playerId","captureAt","getClientInfo","toISOString","player_id","device_type","toLowerCase","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","inputStreamType","publishTracking","body","sendAdLoadedTracking","adLoadedInfo","error","sendAdImpressionTracking","adImpressionInfo","metricEvent","events","ad_url","adUrl","heartbeatData","getAdAudioVolume","adPlayer","getOriginalMutedState","getOriginalVolume","host","timing","preloadPool","adConfig","cueManager","placeholder","inAdBreak","showAds","isShowingPlaceholder","adDetectSentForCurrentBreak","adRequestQueue","adPodQueue","maxPlaceholderDurationMs","debug","config","debugAdTiming","attachImaEventListeners","getAdPlayer","source","adIndex","currentAdIndex","catch","recordPlayedAdDuration","remaining","getRemainingAdMs","consecutiveFailures","log","queuedUrls","hasTimeToStartAnotherAd","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorPayload","errorMessage","errorCode","code","continuousFetchingActive","continuousFetchLoopRunning","vastErrorCode","cause","innerError","causeMessage","String","handleAdFailure","clearAdFailsafeTimer","clearAdRequestWatchdog","activeAdRequestToken","resetGamNoFillCounter","expectedAdBreakDurationMs","getAdBreakEndWallClockMs","scheduleAdStopAtBreakBoundary","setAdVolume","hidePlaceholder","video","muted","newAdPlayer","createAdPlayer","continueLiveStreamDuringAds","recreateAdController","shouldShowPlaceholder","show","preservedMutedState","preservedVolumeState","destroy","shouldContinueLiveStreamDuringAds","setAdPlayer","initialize","updateOriginalMutedState","showPlaceholder","clearPendingAdBreak","prefetchTimerId","clearTimeout","pendingAdBreak","podAssignedByPrefetch","handleAdStart","scheduled","tags","baseVastUrl","adBreakDurationMs","mode","currentMuted","currentVolume","firstAdUrl","usePreloadedAd","preloadedController","preloaded","firstAdUrlArray","preservedMuted","preservedVolume","adVolume","fallbackPreloaded","ap","fallbackError","findCurrentOrNextBreak","currentTime","consumedVmapBreakIds","add","getAdBreakKey","selectVastTagsForBreak","apiVastTagUrl","_marker","durationSeconds","durationMs","isLiveStream","failedVastUrls","clear","temporaryFailureUrls","isLoopRunning","totalAdRequestsInBreak","beginNewAdPod","volume","adBreakPlayedDurationMs","totalAdsInBreak","vastUrl","adController","vastUrls","shift","generateVastUrls","ensureLoadedAdFitsBudget","rejectLoadedAdForDuration","startContinuousFetching","resume","active","preloadPoolLoop","play","markAdStarted","enforceGlobalRateLimit","lastAdRequestTime","requestAds","startPreloadPool","getPreloadedAd","swapToPreloadedAdPlayer","isTemporaryAdError","set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iGAeiEA,UAFxD,4BAAA,gBASP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YArBEC,SAAWC,IAAAA,GAAOC,MAAM;QACxBC,YAAYF,OAAOG,cAAc;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OsG,cAAA,CAAeR,GAAA,CAAId;8CAC/B,IAAI,IAAA,CAAKpE,KAAA,EAAO;;;;;oCAEhB,yBAAA;gCACF;uDACA,IAAA,CAAKZ,MAAA,CAAOwB,mBAAA;iCAEZ,IAAA,CAAK8F,uBAAA,CAAwB3C","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator_exports = {};\n__export(AdBreakOrchestrator_exports, {\n AdBreakOrchestrator: () => AdBreakOrchestrator\n});\nmodule.exports = __toCommonJS(AdBreakOrchestrator_exports);\n\n// src/utils/mqttConfig.ts\nvar DEFAULT_MQTT_CONFIG = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1\n};\nvar mqttConfig = { ...DEFAULT_MQTT_CONFIG };\nfunction isMQTTEnabled() {\n return mqttConfig.enabled;\n}\nfunction buildMQTTBrokerUrl() {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\nfunction buildPlayerTopic(licenseKey, channel) {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n\n// src/utils/mqttClient.ts\nvar import_mqtt = __toESM(require(\"mqtt\"), 1);\nvar LOG = \"[StormcloudVideoPlayer][MQTT]\";\nvar client = null;\nvar status = \"disconnected\";\nfunction initMQTTClient() {\n if (client || !isMQTTEnabled()) return;\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n try {\n client = import_mqtt.default.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5e3,\n connectTimeout: 1e4,\n queueQoSZero: false\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting\\u2026`);\n });\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\nfunction ensureMQTTClient() {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\nfunction publishMQTT(topic, payload) {\n if (!isMQTTEnabled()) {\n return false;\n }\n ensureMQTTClient();\n if (!client) {\n return false;\n }\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n const fingerprintString = JSON.stringify(clientInfo);\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\nfunction canPublish(licenseKey) {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\nasync function buildPlayerMetricEvent(context = {}, flags = {}) {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? (/* @__PURE__ */ new Date()).toISOString();\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...context.inputStreamType ? { input_stream_type: context.inputStreamType } : {}\n };\n}\nfunction publishTracking(licenseKey, channel, body) {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo, context = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp\n });\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp\n }\n ]\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey, context = {}, flags = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/player/PlayerControls.ts\nfunction getAdAudioVolume(adPlayer) {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator = class {\n constructor(host, timing, preloadPool, adConfig, cueManager, placeholder) {\n this.inAdBreak = false;\n this.showAds = false;\n this.isShowingPlaceholder = false;\n this.adDetectSentForCurrentBreak = false;\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.adRequestQueue = [];\n this.adPodQueue = [];\n this.maxPlaceholderDurationMs = 5e3;\n this.pendingAdBreak = null;\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n get debug() {\n return !!this.host.config.debugAdTiming;\n }\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n attachImaEventListeners() {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n this.timing.consecutiveFailures = 0;\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n recreateAdController() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = void 0;\n this.adConfig.podAssignedByPrefetch = false;\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n async handleAdStart(_marker) {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1e3\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled?.durationMs;\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n let firstAdUrl;\n let usePreloadedAd = false;\n let preloadedController;\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n this.attachImaEventListeners();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n preloadedController.resume();\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n await preloadedController.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n await adPlayer.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n swapToPreloadedAdPlayer(preloadedController) {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n startContinuousFetching(baseVastUrl) {\n if (!this.continuousFetchingActive) {\n return;\n }\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n async continuousFetchLoop(baseVastUrl) {\n const epoch = this.timing.adBreakEpoch;\n while (this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n continue;\n }\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n continue;\n }\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n this.adRequestQueue.push(newAdUrl);\n const generationDelay = this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, this.timing.consecutiveFailures), 5e3) : 500;\n await new Promise((resolve) => setTimeout(resolve, generationDelay));\n }\n this.continuousFetchLoopRunning = false;\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.placeholder.hide();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n async tryNextAvailableAdWithRateLimit() {\n if (!this.inAdBreak) {\n return;\n }\n const epoch = this.timing.adBreakEpoch;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(retryCount = 0) {\n if (!this.inAdBreak) {\n return;\n }\n const remaining = this.timing.getRemainingAdMs();\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n this.timing.cleanupTemporaryFailures();\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(preloaded.adController);\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n if (!this.isShowingPlaceholder && remaining > 1e3) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n async playSingleAd(vastTagUrl) {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n this.recreateAdController();\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() }\n ).catch(() => {\n });\n this.timing.clearAdRequestWatchdog();\n if (this.timing.activeAdRequestToken !== requestToken) return;\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(playError)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = error?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n async showPlaceholderAndWaitForAds() {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) return;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n handleAdPodComplete() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n this.timing.resetForBreakEnd();\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.adRequestQueue = [];\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = void 0;\n this.cueManager.scheduledScte35BreakKey = void 0;\n this.adPodQueue = [];\n this.showAds = false;\n this.host.getAdPlayer().stop().catch(() => {\n });\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n const liveSyncPos = this.host.getLiveSyncPosition();\n if (liveSyncPos != null && liveSyncPos > this.host.video.currentTime) {\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] Live break end \\u2014 snapping to live edge: ${this.host.video.currentTime.toFixed(2)}s \\u2192 ${liveSyncPos.toFixed(2)}s`\n );\n }\n this.host.video.currentTime = liveSyncPos;\n }\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {\n });\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {\n });\n }\n }\n handleAdFailure() {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AdBreakOrchestrator\n});\n","import type {\n StormcloudVideoPlayerConfig,\n Scte35Marker,\n AdController,\n} from \"../types\";\nimport {\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport type { AdTimingService } from \"./AdTimingService\";\nimport type { AdPreloadPool } from \"./AdPreloadPool\";\nimport type { AdConfigManager } from \"./AdConfigManager\";\nimport type { Scte35CueManager } from \"./Scte35CueManager\";\nimport type { PlaceholderLayer } from \"./PlaceholderLayer\";\nimport { getAdAudioVolume } from \"./PlayerControls\";\n\nexport interface AdBreakOrchestratorHost {\n readonly config: StormcloudVideoPlayerConfig;\n readonly video: HTMLVideoElement;\n getAdPlayer(): AdController;\n setAdPlayer(player: AdController): void;\n createAdPlayer(continueLiveStreamDuringAds: boolean): AdController;\n shouldContinueLiveStreamDuringAds(): boolean;\n getLiveSyncPosition(): number | undefined;\n generateVastUrls(baseUrl: string, count: number): string[];\n}\n\nexport class AdBreakOrchestrator {\n inAdBreak = false;\n showAds: boolean = false;\n isShowingPlaceholder: boolean = false;\n adDetectSentForCurrentBreak: boolean = false;\n\n private continuousFetchingActive: boolean = false;\n private continuousFetchLoopRunning = false;\n adRequestQueue: string[] = [];\n adPodQueue: string[] = [];\n private readonly maxPlaceholderDurationMs: number = 5000;\n\n pendingAdBreak: {\n marker: Scte35Marker;\n detectedAtFragmentSn?: number;\n vastUrls: string[];\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n prefetchTimerId: number | undefined;\n\n private readonly host: AdBreakOrchestratorHost;\n private readonly timing: AdTimingService;\n private readonly preloadPool: AdPreloadPool;\n private readonly adConfig: AdConfigManager;\n private readonly cueManager: Scte35CueManager;\n private readonly placeholder: PlaceholderLayer;\n\n constructor(\n host: AdBreakOrchestratorHost,\n timing: AdTimingService,\n preloadPool: AdPreloadPool,\n adConfig: AdConfigManager,\n cueManager: Scte35CueManager,\n placeholder: PlaceholderLayer\n ) {\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n\n private get debug(): boolean {\n return !!this.host.config.debugAdTiming;\n }\n\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n\n attachImaEventListeners(): void {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n this.timing.consecutiveFailures = 0;\n\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n\n recreateAdController(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n\n clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = undefined;\n this.adConfig.podAssignedByPrefetch = false;\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n\n async handleAdStart(_marker: Scte35Marker): Promise<void> {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1000\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n\n const adBreakDurationMs =\n _marker.durationSeconds != null\n ? _marker.durationSeconds * 1000\n : scheduled?.durationMs;\n\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n\n if (\n this.timing.expectedAdBreakDurationMs == null &&\n adBreakDurationMs != null\n ) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n let firstAdUrl: string | undefined;\n let usePreloadedAd = false;\n let preloadedController: AdController | undefined;\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n\n this.attachImaEventListeners();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n\n preloadedController.resume();\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n await preloadedController.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n\n await adPlayer.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n\n private swapToPreloadedAdPlayer(preloadedController: AdController): void {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n\n private startContinuousFetching(baseVastUrl: string): void {\n if (!this.continuousFetchingActive) {\n return;\n }\n\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n\n private async continuousFetchLoop(baseVastUrl: string): Promise<void> {\n const epoch = this.timing.adBreakEpoch;\n while (\n this.continuousFetchingActive &&\n this.inAdBreak &&\n epoch === this.timing.adBreakEpoch\n ) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n continue;\n }\n\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise(resolve => setTimeout(resolve, 500));\n continue;\n }\n\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n\n this.adRequestQueue.push(newAdUrl);\n\n const generationDelay = this.timing.consecutiveFailures > 0\n ? Math.min(1000 * Math.pow(2, this.timing.consecutiveFailures), 5000)\n : 500;\n await new Promise(resolve => setTimeout(resolve, generationDelay));\n }\n\n this.continuousFetchLoopRunning = false;\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n\n stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n\n this.placeholder.hide();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n\n async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const epoch = this.timing.adBreakEpoch;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(retryCount: number = 0): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const remaining = this.timing.getRemainingAdMs();\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n this.timing.cleanupTemporaryFailures();\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(preloaded.adController);\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n\n if (!nextAdUrl) continue;\n\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2000) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n\n if (!this.isShowingPlaceholder && remaining > 1000) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n\n async playSingleAd(vastTagUrl: string): Promise<void> {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n\n this.recreateAdController();\n\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: new Date().toISOString() }\n ).catch(() => {});\n\n this.timing.clearAdRequestWatchdog();\n\n if (this.timing.activeAdRequestToken !== requestToken) return;\n\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(playError as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = (error as Error)?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n\n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n\n for (let i = 0; i < maxChecks; i++) {\n await new Promise(resolve => setTimeout(resolve, checkInterval));\n\n if (!this.inAdBreak) return;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n\n handleAdPodComplete(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n\n this.timing.resetForBreakEnd();\n\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.adRequestQueue = [];\n\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = undefined;\n this.cueManager.scheduledScte35BreakKey = undefined;\n this.adPodQueue = [];\n this.showAds = false;\n\n this.host.getAdPlayer().stop().catch(() => {});\n\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n const liveSyncPos = this.host.getLiveSyncPosition();\n if (liveSyncPos != null && liveSyncPos > this.host.video.currentTime) {\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] Live break end — snapping to live edge: ${this.host.video.currentTime.toFixed(2)}s → ${liveSyncPos.toFixed(2)}s`\n );\n }\n this.host.video.currentTime = liveSyncPos;\n }\n\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {});\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {});\n }\n }\n\n handleAdFailure(): void {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n}\n","export const MQTT_CA_CERT_FILE = \"src/certs/emqxsl-ca.crt\";\n\nexport type MQTTConfig = {\n enabled: boolean;\n brokerAddress: string;\n brokerPort: number;\n wsPort: number;\n username: string;\n password: string;\n topicPrefix: string;\n qos: 0 | 1 | 2;\n brokerUrl?: string;\n};\n\nexport const DEFAULT_MQTT_CONFIG: MQTTConfig = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1,\n};\n\nexport const mqttConfig: MQTTConfig = { ...DEFAULT_MQTT_CONFIG };\n\nexport function applyMQTTConfig(overrides: Partial<MQTTConfig>): void {\n Object.assign(mqttConfig, overrides);\n}\n\nexport function isMQTTEnabled(): boolean {\n return mqttConfig.enabled;\n}\n\nexport function buildMQTTBrokerUrl(): string {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\n\nexport function buildPlayerTopic(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\"\n): string {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n","import mqtt from \"mqtt\";\nimport type { MqttClient } from \"mqtt\";\nimport {\n applyMQTTConfig,\n buildMQTTBrokerUrl,\n isMQTTEnabled,\n mqttConfig,\n} from \"./mqttConfig\";\nimport type { MQTTConfig } from \"./mqttConfig\";\n\nconst LOG = \"[StormcloudVideoPlayer][MQTT]\";\n\nexport type MQTTStatus = \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n\nlet client: MqttClient | null = null;\nlet status: MQTTStatus = \"disconnected\";\n\nexport function getMQTTStatus(): MQTTStatus {\n return status;\n}\n\nexport function isMQTTConnected(): boolean {\n return status === \"connected\" && client !== null && client.connected;\n}\n\nexport function isMQTTConfigured(): boolean {\n return isMQTTEnabled();\n}\n\nexport function configureMQTT(overrides: Partial<MQTTConfig>): void {\n applyMQTTConfig(overrides);\n disconnectMQTT();\n}\n\nexport function initMQTTClient(): void {\n if (client || !isMQTTEnabled()) return;\n\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n\n try {\n client = mqtt.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5000,\n connectTimeout: 10_000,\n queueQoSZero: false,\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting…`);\n });\n\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\n\nexport function ensureMQTTClient(): void {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\n\nexport function publishMQTT(\n topic: string,\n payload: Record<string, unknown>\n): boolean {\n if (!isMQTTEnabled()) {\n return false;\n }\n\n ensureMQTTClient();\n\n if (!client) {\n return false;\n }\n\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\nexport function disconnectMQTT(): void {\n if (client) {\n client.end(true);\n client = null;\n status = \"disconnected\";\n }\n}\n","import type {\n ClientInfo,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n PlayerAnalyticsContext,\n} from \"../types\";\nimport { buildPlayerTopic, isMQTTEnabled } from \"./mqttConfig\";\nimport { ensureMQTTClient, publishMQTT } from \"./mqttClient\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n const fingerprintString = JSON.stringify(clientInfo);\n\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(fingerprintString);\n } else {\n const utf8 = unescape(encodeURIComponent(fingerprintString));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n const hashHex = Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n cachedBrowserId = hashHex;\n return hashHex;\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < fingerprintString.length; i++) {\n const char = fingerprintString.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n cachedBrowserId = (fallbackHash + timestamp + random).padEnd(64, \"0\");\n return cachedBrowserId;\n}\n\ntype PlayerMetricFlags = {\n adLoaded?: boolean;\n adDetect?: boolean;\n captureAt?: string;\n};\n\nfunction canPublish(licenseKey: string | undefined): licenseKey is string {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\n\nasync function buildPlayerMetricEvent(\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<Record<string, unknown>> {\n const clientInfo = getClientInfo();\n const playerId = await getBrowserID(clientInfo);\n const captureAt = flags.captureAt ?? new Date().toISOString();\n\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...(context.inputStreamType\n ? { input_stream_type: context.inputStreamType }\n : {}),\n };\n}\n\nfunction publishTracking(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\",\n body: Record<string, unknown>\n): void {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\n\nexport async function sendInitialTracking(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n adLoaded: false,\n adDetect: false,\n });\n\n publishTracking(licenseKey, \"metrics\", {\n events: [metricEvent],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp,\n });\n\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp,\n },\n ],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","import type { AdController } from \"../types\";\n\nexport function getAdAudioVolume(adPlayer: AdController): number {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\nexport function toggleMute(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (adPlayer.isAdPlaying()) {\n const newMutedState = !adPlayer.getOriginalMutedState();\n const restoreVolume = adPlayer.getOriginalVolume() || 1;\n\n adPlayer.updateOriginalMutedState(newMutedState, video.volume);\n adPlayer.setAdVolume(newMutedState ? 0 : restoreVolume);\n\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n video.muted = !video.muted;\n adPlayer.updateOriginalMutedState(video.muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", video.muted);\n }\n }\n}\n\nexport function toggleFullscreen(\n video: HTMLVideoElement,\n debug: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n}\n\nexport function isMuted(\n video: HTMLVideoElement,\n adPlayer: AdController\n): boolean {\n if (adPlayer.isAdPlaying()) {\n return adPlayer.getOriginalMutedState();\n }\n return video.muted;\n}\n\nexport function setMuted(\n video: HTMLVideoElement,\n adPlayer: AdController,\n muted: boolean,\n debug: boolean\n): void {\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying && muted === video.muted) {\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n\n video.muted = muted;\n\n if (adPlaying) {\n adPlayer.updateOriginalMutedState(muted, video.volume);\n adPlayer.setAdVolume(muted ? 0 : 1);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted,\n });\n }\n return;\n }\n\n adPlayer.updateOriginalMutedState(muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n}\n\nexport function setVolume(\n video: HTMLVideoElement,\n adPlayer: AdController,\n volume: number,\n debug: boolean\n): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying) {\n adPlayer.setAdVolume(clampedVolume);\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n video.volume = clampedVolume;\n video.muted = clampedVolume === 0;\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n}\n\nexport function getVolume(\n video: HTMLVideoElement,\n adPlayer: AdController\n): number {\n const adPlaying = adPlayer.isAdPlaying();\n if (adPlaying) {\n return adPlayer.getAdVolume();\n }\n return video.volume;\n}\n\nexport function isFullscreen(): boolean {\n return !!document.fullscreenElement;\n}\n\nexport function resizePlayer(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (adPlayer && adPlayer.isAdPlaying()) {\n const width = video.clientWidth || 640;\n const height = video.clientHeight || 480;\n\n if (debug) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n adPlayer.resize(width, height);\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/ubuntu24-new/Dev/stormcloud-vp/lib/player/AdBreakOrchestrator.cjs","../../src/player/AdBreakOrchestrator.ts","../../src/utils/mqttConfig.ts","../../src/utils/mqttClient.ts","../../src/utils/vastEnvironmentSignals.ts","../../src/utils/tracking.ts","../../src/player/PlayerControls.ts"],"names":["__create","Object","create","__defProp","defineProperty","__getOwnPropDesc","__getOwnPropNames","getOwnPropertyDescriptor","getOwnPropertyNames","__getProtoOf","getPrototypeOf","__hasOwnProp","prototype","hasOwnProperty","__export","target","all","name","get","enumerable","__copyProps","from","to","except","desc","key","call","__toESM","mod","isNodeMode","__esModule","value","__toCommonJS","AdBreakOrchestrator_exports","AdBreakOrchestrator","module","exports","DEFAULT_MQTT_CONFIG","enabled","brokerAddress","brokerPort","wsPort","username","password","topicPrefix","mqttConfig","buildMQTTBrokerUrl","brokerUrl","buildPlayerTopic","licenseKey","channel","import_mqtt","require","LOG","client","status","initMQTTClient","url","isMQTTEnabled","clientId","Math","random","toString","slice","mqtt","connect","keepalive","clean","reconnectPeriod","connectTimeout","queueQoSZero","err","console","warn","on","info","message","ensureMQTTClient","publishMQTT","topic","payload","publish","JSON","stringify","qos","PLAYER_ID_STORAGE_KEY","DEVICE_ID_STORAGE_KEYS","isMacroPlaceholder","source","inferDeviceIdType","navigator","ua","userAgent","test","resolveNativeDeviceId","bridgeSignals","readNativeBridgeSignals","platformDevice","readPlatformNativeDeviceId","deviceId","readStoredDeviceId","isZeroedAdId","getOrCreateStoredUuid","storageKey","window","existing","readStoredString","id","createUuid","localStorage","setItem","crypto","randomUUID","replace","char","floor","nibble","adinfo","webapis","tifa","getTIFA","lat","isLATEnabled","deviceIdType","limitAdTracking","webOSDev","lgudid","LGUDID","roku","Roku","rida","getPublisherUniqueId","ZEROED_AD_ID_PATTERNS","Set","t","trim","has","toLowerCase","candidates","__STORMCLOUD_CTV_AD_INFO__","__STORMCLOUD_CTV__","stormcloudCtv","AiryTV","Android","webOS","tizen","amazon","filter","Boolean","contentUrl","readBridgeValue","appId","appName","readBridgeBoolean","keys","result","normalized","normalizeBoolean","getItem","cachedBrowserId","buildAnalyticsContext","config","context","debugAdTiming","isLiveStream","inputStreamType","getClientInfo","screen","platform","vendor","maxTouchPoints","memory","deviceMemory","hardwareConcurrency","screenInfo","width","height","availWidth","availHeight","orientation","type","pixelDepth","deviceType","brand","os","model","isSmartTV","isAndroid","isWebView","isWebApp","includes","webosMatch","match","tizenMatch","tvMatch","androidModelMatch","path","location","timestamp","clientInfo","log","sendAdLoadedTracking","outerHeight","outerWidth","matchMedia","matches","standalone","angle","substring","domain","hostname","origin","pathname","language","languages","join","cookieEnabled","doNotTrack","referrer","document","visibilityState","sha256Hex","input","encodedData","utf8","buffer","i","hashBuffer","hash","fallbackHash","subtle","digest","Uint8Array","TextEncoder","encode","unescape","encodeURIComponent","length","charCodeAt","Array","map","b","padStart","abs","Date","now","padEnd","resolvePlayerIdentitySeed","nativeDeviceId","persistedId","getBrowserID","buildPlayerMetricEvent","flags","playerId","captureAt","toISOString","player_id","ad_loaded","adLoaded","ad_detect","adDetect","capture_at","input_stream_type","publishTracking","body","adLoadedInfo","error","sendHeartbeat","sendAdImpressionTracking","adImpressionInfo","metricEvent","canPublish","events","ad_played_count","ad_url","adUrl","heartbeatData","getAdAudioVolume","adPlayer","getOriginalMutedState","getOriginalVolume","host","timing","preloadPool","adConfig","cueManager","placeholder","inAdBreak","showAds","isShowingPlaceholder","adDetectSentForCurrentBreak","continuousFetchingActive","continuousFetchLoopRunning","adRequestQueue","adPodQueue","maxPlaceholderDurationMs","pendingAdBreak","debug","analyticsContext","attachImaEventListeners","getAdPlayer","adIndex","currentAdIndex","catch","remaining","getRemainingAdMs","consecutiveFailures","queuedUrls","hasTimeToStartAnotherAd","tryNextAvailableAdWithRateLimit","handleAdPodComplete","errorMessage","errorPayload","errorCode","code","vastErrorCode","cause","innerError","causeMessage","String","handleAdFailure","clearAdFailsafeTimer","clearAdRequestWatchdog","activeAdRequestToken","expectedAdBreakDurationMs","getAdBreakEndWallClockMs","scheduleAdStopAtBreakBoundary","hidePlaceholder","video","muted","newAdPlayer","scheduled","temporaryFailureUrls","clear","recordPlayedAdDuration","recreateAdController","shouldShowPlaceholder","show","showPlaceholder","preservedMutedState","destroy","continueLiveStreamDuringAds","shouldContinueLiveStreamDuringAds","createAdPlayer","setAdPlayer","initialize","clearPendingAdBreak","prefetchTimerId","clearTimeout","pendingScte35CueKey","handleAdStart","_marker","tags","baseVastUrl","adBreakDurationMs","mode","currentMuted","currentVolume","firstAdUrl","usePreloadedAd","preloadedController","preloaded","firstAdUrlArray","preservedMuted","preservedVolume","adVolume","fallbackPreloaded","ap","fallbackError","consumedVmapBreakIds","add","getAdBreakKey","selectVastTagsForBreak","apiVastTagUrl","durationSeconds","durationMs","failedVastUrls","totalAdRequestsInBreak","podAssignedByPrefetch","beginNewAdPod","volume","updateOriginalMutedState","adBreakPlayedDurationMs","totalAdsInBreak","getPreloadedAd","vastUrl","adController","vastUrls","shift","generateVastUrls","ensureLoadedAdFitsBudget","startContinuousFetching","resume","active","isLoopRunning","preloadPoolLoop","play","markAdStarted","setAdVolume","enforceGlobalRateLimit","lastAdRequestTime","requestAds","rejectLoadedAdForDuration"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YACIA,SAAWC,OAAOC,MAAM;QACxBC,YAAYF,OAAOG,cAAc;IACrC,EAAIC,eAAAA,CACJ,EAAIC,UADmBL,OAAOM,GACNN,OAAOO,cADuB,KACJ;IAClD,EAAIC,EAAAA,aAAeR,OAAOS,cAAc;QACpCC,IAAAA,OAAAA,EAAeV,KAAAA,EAAOW,EAAAA,OAAS,CAACC,cAAc;QAC9CC,IAAAA,MAAAA,CAAW,kBAACC,QAAQC;YACtB,EAAK,EAAIC,OAAAA,CAAQD,IACfb,EAAAA,KAAAA,GAAUY,QAAQE,MAAM,GAAA,KAAA,aA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OAAOW,WAAA;4CAAc,GAC1E,IAAA,CAAK2C,gBAAA,EACLK,KAAA,CAAM,YAAO;8CAEf,IAAI,IAAA,CAAKN,IACPjO,CADO,EAAO,KACNgI,GAAA,CAAI,KAAA,OAAA,WAAA,mBAAA,OAAA,IAAA,CAAA,cAAA,CAAA,MAAA,EAAA,0BAAA,OAAA,IAAA,CAAA,MAAA,CAAA,mBAAA,2BACd,EAAA,GAAA,IAAA;wBAAA,YAAA,qBAAA,IAAA,CAAA,cAAA;oBAAA,IAAA,CAAA;;;;8CAGE,IAAA,CAAKkF,MAAA,CAAOwH,yBAAA,CAA0B5H;8CACtC,IAAA,CAAKyD,oBAAA;4CACL,IAAA,CAAKwD,uBAAA,CAAwBtC;4CAC7B,WAAA,IAAA;;gDAAM,IAAA,CAAK5C,+BAAA;;;4CAAX;0CACA;;;;;;;uDAGF,IAAA,CAAK3B,MAAA,CAAOwB,mBAAA,GAAsB;iCAClC,IAAA,CAAKqF,uBAAA,CAAwBtC","sourcesContent":["\"use strict\";\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", { value: mod, enumerable: true }) : target,\n mod\n));\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator_exports = {};\n__export(AdBreakOrchestrator_exports, {\n AdBreakOrchestrator: () => AdBreakOrchestrator\n});\nmodule.exports = __toCommonJS(AdBreakOrchestrator_exports);\n\n// src/utils/mqttConfig.ts\nvar DEFAULT_MQTT_CONFIG = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1\n};\nvar mqttConfig = { ...DEFAULT_MQTT_CONFIG };\nfunction isMQTTEnabled() {\n return mqttConfig.enabled;\n}\nfunction buildMQTTBrokerUrl() {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\nfunction buildPlayerTopic(licenseKey, channel) {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n\n// src/utils/mqttClient.ts\nvar import_mqtt = __toESM(require(\"mqtt\"), 1);\nvar LOG = \"[StormcloudVideoPlayer][MQTT]\";\nvar client = null;\nvar status = \"disconnected\";\nfunction initMQTTClient() {\n if (client || !isMQTTEnabled()) return;\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n try {\n client = import_mqtt.default.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5e3,\n connectTimeout: 1e4,\n queueQoSZero: false\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting\\u2026`);\n });\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\nfunction ensureMQTTClient() {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\nfunction publishMQTT(topic, payload) {\n if (!isMQTTEnabled()) {\n return false;\n }\n ensureMQTTClient();\n if (!client) {\n return false;\n }\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\n// src/utils/vastEnvironmentSignals.ts\nvar PLAYER_ID_STORAGE_KEY = \"stormcloud.player.id\";\nvar DEVICE_ID_STORAGE_KEYS = [\n \"rdid\",\n \"ifa\",\n \"advertisingId\",\n \"advertising_id\",\n \"deviceAdvertisingId\",\n \"aaid\",\n \"adid\",\n \"rida\",\n \"tifa\",\n \"lgudid\"\n];\nfunction inferDeviceIdType() {\n if (typeof navigator === \"undefined\") {\n return void 0;\n }\n const ua = navigator.userAgent;\n if (/Roku/i.test(ua)) return \"rida\";\n if (/Tizen|Samsung/i.test(ua)) return \"tifa\";\n if (/AppleTV|Apple TV/i.test(ua)) return \"tvOS\";\n if (/AFT|Fire TV|Amazon/i.test(ua)) return \"afai\";\n if (/Web0S|webOS|LG Browser|LGSTB|LGE/i.test(ua)) return \"lgudid\";\n if (/Android|Google TV/i.test(ua)) return \"aaid\";\n if (/iPhone|iPad|iPod/i.test(ua)) return \"idfa\";\n return void 0;\n}\nfunction resolveNativeDeviceId() {\n const bridgeSignals = readNativeBridgeSignals();\n const platformDevice = readPlatformNativeDeviceId();\n const deviceId = bridgeSignals.deviceId || readStoredDeviceId() || platformDevice.deviceId;\n if (!deviceId || isMacroPlaceholder(deviceId) || isZeroedAdId(deviceId)) {\n return void 0;\n }\n return deviceId;\n}\nfunction getOrCreateStoredUuid(storageKey) {\n if (typeof window === \"undefined\") {\n return void 0;\n }\n const existing = readStoredString(storageKey);\n if (existing) {\n return existing;\n }\n const id = createUuid();\n try {\n window.localStorage?.setItem(storageKey, id);\n } catch {\n }\n return id;\n}\nfunction createUuid() {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (char) => {\n const value = Math.floor(Math.random() * 16);\n const nibble = char === \"x\" ? value : value & 3 | 8;\n return nibble.toString(16);\n });\n}\nfunction readPlatformNativeDeviceId() {\n if (typeof window === \"undefined\") return {};\n try {\n const adinfo = window.webapis?.adinfo;\n if (adinfo) {\n const tifa = typeof adinfo.getTIFA === \"function\" ? adinfo.getTIFA() : adinfo.tifa;\n if (typeof tifa === \"string\" && tifa && !isMacroPlaceholder(tifa)) {\n const lat = typeof adinfo.isLATEnabled === \"function\" ? adinfo.isLATEnabled() : void 0;\n return {\n deviceId: tifa,\n deviceIdType: \"tifa\",\n ...typeof lat === \"boolean\" ? { limitAdTracking: lat } : {}\n };\n }\n }\n } catch {\n }\n try {\n const webOSDev = window.webOSDev;\n if (webOSDev) {\n const lgudid = typeof webOSDev.LGUDID === \"function\" ? webOSDev.LGUDID() : webOSDev.lgudid ?? webOSDev.LGUDID;\n if (typeof lgudid === \"string\" && lgudid) {\n if (isZeroedAdId(lgudid)) {\n return { deviceIdType: \"lgudid\", limitAdTracking: true };\n }\n if (!isMacroPlaceholder(lgudid)) {\n return { deviceId: lgudid, deviceIdType: \"lgudid\", limitAdTracking: false };\n }\n }\n }\n } catch {\n }\n try {\n const roku = window.Roku;\n if (roku) {\n const rida = typeof roku.getPublisherUniqueId === \"function\" ? roku.getPublisherUniqueId() : roku.rida;\n if (typeof rida === \"string\" && rida && !isMacroPlaceholder(rida)) {\n return { deviceId: rida, deviceIdType: \"rida\", limitAdTracking: false };\n }\n }\n } catch {\n }\n return {};\n}\nvar ZEROED_AD_ID_PATTERNS = /* @__PURE__ */ new Set([\n \"38400000-8cf0-11bd-b23e-10b96e40000d\",\n \"00000000-0000-0000-0000-000000000000\"\n]);\nfunction isMacroPlaceholder(value) {\n const t = value.trim();\n return !t || /^(\\[[^\\]]*\\]|\\{[^}]*\\}|%%[^%]*%%)$/.test(t) || /^(unknown|null|undefined|none|n\\/a|\\$\\{[^}]+\\})$/i.test(t) || ZEROED_AD_ID_PATTERNS.has(t.toLowerCase());\n}\nfunction isZeroedAdId(value) {\n return ZEROED_AD_ID_PATTERNS.has(value.trim().toLowerCase());\n}\nfunction readNativeBridgeSignals() {\n if (typeof window === \"undefined\") {\n return {};\n }\n const candidates = [\n window.__STORMCLOUD_CTV_AD_INFO__,\n window.__STORMCLOUD_CTV__,\n window.stormcloudCtv,\n window.AiryTV,\n window.Android,\n window.webOS,\n window.tizen,\n window.amazon\n ].filter(Boolean);\n for (const source of candidates) {\n const contentUrl = readBridgeValue(source, [\"contentUrl\", \"url\", \"videoUrl\", \"canonicalUrl\"]) || void 0;\n const appId = readBridgeValue(source, [\"appId\", \"msid\", \"applicationId\", \"packageName\"]) || void 0;\n const appName = readBridgeValue(source, [\"appName\", \"an\", \"applicationName\"]) || void 0;\n const deviceId = readBridgeValue(source, [\n \"rdid\",\n \"ifa\",\n \"advertisingId\",\n \"adId\",\n \"deviceId\",\n \"lgudid\",\n \"LGUDID\",\n \"tifa\",\n \"rida\",\n \"afai\",\n \"aaid\"\n ]) || void 0;\n if (!contentUrl && !deviceId && !appId && !appName) continue;\n const deviceIdType = readBridgeValue(source, [\n \"idtype\",\n \"deviceIdType\",\n \"advertisingIdType\",\n \"idType\"\n ]) || inferDeviceIdType();\n const limitAdTracking = readBridgeBoolean(source, [\n \"is_lat\",\n \"limitAdTracking\",\n \"limitedAdTracking\",\n \"lat\"\n ]);\n return {\n ...contentUrl ? { contentUrl } : {},\n ...appId ? { appId } : {},\n ...appName ? { appName } : {},\n ...deviceId ? { deviceId } : {},\n ...deviceId && deviceIdType ? { deviceIdType } : {},\n ...deviceId && limitAdTracking != null ? { limitAdTracking } : {}\n };\n }\n return {};\n}\nfunction readBridgeValue(source, keys) {\n for (const key of keys) {\n const value = source?.[key];\n if (typeof value === \"string\" && value) {\n return value;\n }\n if (typeof value === \"function\") {\n try {\n const result = value.call(source);\n if (typeof result === \"string\" && result) {\n return result;\n }\n } catch {\n }\n }\n }\n return void 0;\n}\nfunction readBridgeBoolean(source, keys) {\n for (const key of keys) {\n const value = source?.[key];\n const normalized = normalizeBoolean(value);\n if (normalized != null) {\n return normalized;\n }\n if (typeof value === \"function\") {\n try {\n const result = normalizeBoolean(value.call(source));\n if (result != null) {\n return result;\n }\n } catch {\n }\n }\n }\n return void 0;\n}\nfunction readStoredDeviceId() {\n for (const key of DEVICE_ID_STORAGE_KEYS) {\n const value = readStoredString(key);\n if (value) {\n return value;\n }\n }\n return void 0;\n}\nfunction readStoredString(key) {\n if (typeof window === \"undefined\") {\n return void 0;\n }\n try {\n const value = window.localStorage?.getItem(key);\n return value || void 0;\n } catch {\n return void 0;\n }\n}\nfunction normalizeBoolean(value) {\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n const normalized = value.toLowerCase();\n if (normalized === \"1\" || normalized === \"true\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"0\" || normalized === \"false\" || normalized === \"no\") {\n return false;\n }\n }\n return void 0;\n}\n\n// src/utils/tracking.ts\nvar cachedBrowserId = null;\nfunction buildAnalyticsContext(config) {\n const context = {};\n if (config.debugAdTiming) {\n context.debugAdTiming = true;\n }\n if (config.isLiveStream !== void 0) {\n context.inputStreamType = config.isLiveStream ? \"live\" : \"vod\";\n }\n return context;\n}\nfunction getClientInfo() {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = navigator.deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: screen?.orientation?.type || \"\",\n pixelDepth: screen?.pixelDepth\n };\n let deviceType = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim() : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Android\") && (ua.includes(\"NetCast\") || ua.includes(\"LG\"))) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n if (ua.includes(\"Android\") && (maxTouchPoints === 0 || ua.includes(\"Google TV\") || ua.includes(\"XiaoMi\"))) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n isWebApp = window.matchMedia(\"(display-mode: standalone)\").matches || window.navigator.standalone === true || window.screen?.orientation?.angle !== void 0;\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState\n };\n}\nasync function sha256Hex(input) {\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n let encodedData;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(input);\n } else {\n const utf8 = unescape(encodeURIComponent(input));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n let hash = 0;\n for (let i = 0; i < input.length; i++) {\n const char = input.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n return (fallbackHash + timestamp + random).padEnd(64, \"0\");\n}\nfunction resolvePlayerIdentitySeed(clientInfo) {\n const nativeDeviceId = resolveNativeDeviceId();\n if (nativeDeviceId) {\n return `device:${nativeDeviceId}`;\n }\n const persistedId = getOrCreateStoredUuid(PLAYER_ID_STORAGE_KEY);\n if (persistedId) {\n return `persisted:${persistedId}`;\n }\n return `fingerprint:${JSON.stringify(clientInfo)}`;\n}\nasync function getBrowserID(clientInfo) {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n cachedBrowserId = await sha256Hex(resolvePlayerIdentitySeed(clientInfo));\n return cachedBrowserId;\n}\nfunction canPublish(licenseKey) {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\nasync function buildPlayerMetricEvent(context = {}, flags = {}) {\n const clientInfo = getClientInfo();\n const debugAdTiming = !!context.debugAdTiming;\n if (debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] clientInfo: \", JSON.stringify(clientInfo, null, 2));\n }\n const playerId = await getBrowserID(clientInfo);\n if (debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] playerId: \", playerId);\n }\n const captureAt = flags.captureAt ?? (/* @__PURE__ */ new Date()).toISOString();\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...context.inputStreamType ? { input_stream_type: context.inputStreamType } : {}\n };\n}\nfunction publishTracking(licenseKey, channel, body) {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\nasync function sendAdLoadedTracking(licenseKey, adLoadedInfo, context = {}) {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\nasync function sendAdImpressionTracking(licenseKey, adImpressionInfo, context = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp\n });\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp\n }\n ]\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\nasync function sendHeartbeat(licenseKey, context = {}, flags = {}) {\n if (!canPublish(licenseKey)) return;\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n\n// src/player/PlayerControls.ts\nfunction getAdAudioVolume(adPlayer) {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\n// src/player/AdBreakOrchestrator.ts\nvar AdBreakOrchestrator = class {\n constructor(host, timing, preloadPool, adConfig, cueManager, placeholder) {\n this.inAdBreak = false;\n this.showAds = false;\n this.isShowingPlaceholder = false;\n this.adDetectSentForCurrentBreak = false;\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.adRequestQueue = [];\n this.adPodQueue = [];\n this.maxPlaceholderDurationMs = 5e3;\n this.pendingAdBreak = null;\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n get debug() {\n return !!this.host.config.debugAdTiming;\n }\n get analyticsContext() {\n return buildAnalyticsContext(this.host.config);\n }\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n attachImaEventListeners() {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n this.timing.consecutiveFailures = 0;\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload) => {\n let errorMessage = \"Ad playback failed\";\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : cause.message || String(cause);\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n if (!this.inAdBreak) {\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n recreateAdController() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n clearPendingAdBreak() {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = void 0;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = void 0;\n this.adConfig.podAssignedByPrefetch = false;\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n async handleAdStart(_marker) {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1e3\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n let baseVastUrl;\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n const adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled?.durationMs;\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n let firstAdUrl;\n let usePreloadedAd = false;\n let preloadedController;\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n this.attachImaEventListeners();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n preloadedController.resume();\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n await preloadedController.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n await adPlayer.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n swapToPreloadedAdPlayer(preloadedController) {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n startContinuousFetching(baseVastUrl) {\n if (!this.continuousFetchingActive) {\n return;\n }\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n async continuousFetchLoop(baseVastUrl) {\n const epoch = this.timing.adBreakEpoch;\n while (this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1e3));\n continue;\n }\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n continue;\n }\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n this.adRequestQueue.push(newAdUrl);\n const generationDelay = this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, this.timing.consecutiveFailures), 5e3) : 500;\n await new Promise((resolve) => setTimeout(resolve, generationDelay));\n }\n this.continuousFetchLoopRunning = false;\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n stopContinuousFetching() {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n this.placeholder.hide();\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n async tryNextAvailableAdWithRateLimit() {\n if (!this.inAdBreak) {\n return;\n }\n const epoch = this.timing.adBreakEpoch;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n }\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n return this.tryNextAvailableAd(0);\n }\n async tryNextAvailableAd(retryCount = 0) {\n if (!this.inAdBreak) {\n return;\n }\n const remaining = this.timing.getRemainingAdMs();\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n this.timing.cleanupTemporaryFailures();\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n this.swapToPreloadedAdPlayer(preloaded.adController);\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n if (!this.isShowingPlaceholder && remaining > 1e3) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n async playSingleAd(vastTagUrl) {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n this.recreateAdController();\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: (/* @__PURE__ */ new Date()).toISOString() },\n this.analyticsContext\n ).catch(() => {\n });\n this.timing.clearAdRequestWatchdog();\n if (this.timing.activeAdRequestToken !== requestToken) return;\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(playError)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = error?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n if (this.timing.isTemporaryAdError(error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n async showPlaceholderAndWaitForAds() {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n if (waitTime < 1e3) {\n this.handleAdPodComplete();\n return;\n }\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n for (let i = 0; i < maxChecks; i++) {\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n if (!this.inAdBreak) return;\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = error.message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n handleAdPodComplete() {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n this.timing.resetForBreakEnd();\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n this.adRequestQueue = [];\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = void 0;\n this.cueManager.scheduledScte35BreakKey = void 0;\n this.adPodQueue = [];\n this.showAds = false;\n this.host.getAdPlayer().stop().catch(() => {\n });\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n const liveSyncPos = this.host.getLiveSyncPosition();\n if (liveSyncPos != null && liveSyncPos > this.host.video.currentTime) {\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] Live break end \\u2014 snapping to live edge: ${this.host.video.currentTime.toFixed(2)}s \\u2192 ${liveSyncPos.toFixed(2)}s`\n );\n }\n this.host.video.currentTime = liveSyncPos;\n }\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {\n });\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {\n });\n }\n }\n handleAdFailure() {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n};\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AdBreakOrchestrator\n});\n","import type {\n StormcloudVideoPlayerConfig,\n Scte35Marker,\n AdController,\n} from \"../types\";\nimport {\n buildAnalyticsContext,\n sendAdLoadedTracking,\n sendAdImpressionTracking,\n} from \"../utils/tracking\";\nimport type { AdTimingService } from \"./AdTimingService\";\nimport type { AdPreloadPool } from \"./AdPreloadPool\";\nimport type { AdConfigManager } from \"./AdConfigManager\";\nimport type { Scte35CueManager } from \"./Scte35CueManager\";\nimport type { PlaceholderLayer } from \"./PlaceholderLayer\";\nimport { getAdAudioVolume } from \"./PlayerControls\";\n\nexport interface AdBreakOrchestratorHost {\n readonly config: StormcloudVideoPlayerConfig;\n readonly video: HTMLVideoElement;\n getAdPlayer(): AdController;\n setAdPlayer(player: AdController): void;\n createAdPlayer(continueLiveStreamDuringAds: boolean): AdController;\n shouldContinueLiveStreamDuringAds(): boolean;\n getLiveSyncPosition(): number | undefined;\n generateVastUrls(baseUrl: string, count: number): string[];\n}\n\nexport class AdBreakOrchestrator {\n inAdBreak = false;\n showAds: boolean = false;\n isShowingPlaceholder: boolean = false;\n adDetectSentForCurrentBreak: boolean = false;\n\n private continuousFetchingActive: boolean = false;\n private continuousFetchLoopRunning = false;\n adRequestQueue: string[] = [];\n adPodQueue: string[] = [];\n private readonly maxPlaceholderDurationMs: number = 5000;\n\n pendingAdBreak: {\n marker: Scte35Marker;\n detectedAtFragmentSn?: number;\n vastUrls: string[];\n isFetching: boolean;\n fetchStartTime?: number;\n } | null = null;\n prefetchTimerId: number | undefined;\n\n private readonly host: AdBreakOrchestratorHost;\n private readonly timing: AdTimingService;\n private readonly preloadPool: AdPreloadPool;\n private readonly adConfig: AdConfigManager;\n private readonly cueManager: Scte35CueManager;\n private readonly placeholder: PlaceholderLayer;\n\n constructor(\n host: AdBreakOrchestratorHost,\n timing: AdTimingService,\n preloadPool: AdPreloadPool,\n adConfig: AdConfigManager,\n cueManager: Scte35CueManager,\n placeholder: PlaceholderLayer\n ) {\n this.host = host;\n this.timing = timing;\n this.preloadPool = preloadPool;\n this.adConfig = adConfig;\n this.cueManager = cueManager;\n this.placeholder = placeholder;\n }\n\n private get debug(): boolean {\n return !!this.host.config.debugAdTiming;\n }\n\n private get analyticsContext() {\n return buildAnalyticsContext(this.host.config);\n }\n\n // ───────────────────────────────────────────────────────────────\n // IMA event listeners\n // ───────────────────────────────────────────────────────────────\n\n attachImaEventListeners(): void {\n const adPlayer = this.host.getAdPlayer();\n adPlayer.on(\"all_ads_completed\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n this.timing.consecutiveFailures = 0;\n\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] all_ads_completed event received - remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.inAdBreak) {\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n }\n });\n adPlayer.on(\"ad_error\", (errorPayload?: any) => {\n let errorMessage = \"Ad playback failed\";\n\n if (errorPayload) {\n const errorCode = errorPayload.code || errorPayload.errorCode || \"unknown\";\n const vastErrorCode = errorPayload.vastErrorCode;\n const message = errorPayload.message || errorPayload.errorMessage || \"Unknown error\";\n const cause = errorPayload.cause || errorPayload.innerError || errorPayload.error;\n\n errorMessage = `Ad error: AdError ${errorCode}: ${message}`;\n\n if (vastErrorCode && vastErrorCode !== \"N/A\" && vastErrorCode !== errorCode) {\n errorMessage += ` (VAST Error Code: ${vastErrorCode})`;\n }\n\n if (cause) {\n const causeMessage = typeof cause === \"string\" ? cause : (cause.message || String(cause));\n errorMessage += `. Caused by: ${causeMessage}`;\n }\n }\n\n console.error(\"[AD-ERROR]\", errorMessage, errorPayload || \"\");\n this.handleAdFailure();\n });\n adPlayer.on(\"content_pause\", () => {\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = true;\n this.timing.resetGamNoFillCounter();\n\n if (this.inAdBreak && this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)\");\n }\n }\n\n this.host.getAdPlayer().setAdVolume(getAdAudioVolume(this.host.getAdPlayer()));\n\n if (this.isShowingPlaceholder) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Hiding placeholder - new ads starting\");\n }\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n });\n adPlayer.on(\"content_resume\", () => {\n sendAdImpressionTracking(\n this.host.config.licenseKey,\n { source: \"hls\", adIndex: this.timing.currentAdIndex, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n\n if (!this.host.video.muted) {\n this.host.video.muted = true;\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)\");\n }\n }\n\n this.timing.clearAdFailsafeTimer();\n this.timing.clearAdRequestWatchdog();\n this.timing.activeAdRequestToken = null;\n this.showAds = false;\n\n if (!this.inAdBreak) {\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n\n this.timing.recordPlayedAdDuration(this.host.getAdPlayer());\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] content_resume event: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n this.handleAdPodComplete();\n }\n });\n }\n\n recreateAdController(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Recreating AdController for new ad\");\n }\n\n const shouldShowPlaceholder = this.inAdBreak && this.showAds;\n const adPlayer = this.host.getAdPlayer();\n if (shouldShowPlaceholder && adPlayer) {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Showing placeholder before destroying old AdController\");\n }\n this.placeholder.show();\n adPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n\n const preservedMutedState = adPlayer.getOriginalMutedState();\n const preservedVolumeState = adPlayer.getOriginalVolume();\n\n if (adPlayer) {\n try {\n adPlayer.destroy();\n this.host.video.muted = true;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[StormcloudVideoPlayer] Error destroying old AdController:\", error);\n }\n }\n }\n\n const continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();\n const newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);\n this.host.setAdPlayer(newAdPlayer);\n\n newAdPlayer.initialize();\n newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);\n this.attachImaEventListeners();\n\n if (shouldShowPlaceholder) {\n this.placeholder.show();\n newAdPlayer.showPlaceholder();\n this.isShowingPlaceholder = true;\n }\n }\n\n clearPendingAdBreak(): void {\n if (this.prefetchTimerId != null) {\n clearTimeout(this.prefetchTimerId);\n this.prefetchTimerId = undefined;\n }\n this.pendingAdBreak = null;\n this.cueManager.pendingScte35CueKey = undefined;\n this.adConfig.podAssignedByPrefetch = false;\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break start\n // ───────────────────────────────────────────────────────────────\n\n async handleAdStart(_marker: Scte35Marker): Promise<void> {\n const scheduled = this.adConfig.findCurrentOrNextBreak(\n this.host.video.currentTime * 1000\n );\n if (scheduled) {\n this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));\n }\n const tags = this.adConfig.selectVastTagsForBreak(scheduled);\n\n let baseVastUrl: string;\n\n if (tags && tags.length > 0 && tags[0]) {\n baseVastUrl = tags[0];\n } else if (this.adConfig.apiVastTagUrl) {\n baseVastUrl = this.adConfig.apiVastTagUrl;\n } else {\n this.clearPendingAdBreak();\n return;\n }\n\n const adBreakDurationMs =\n _marker.durationSeconds != null\n ? _marker.durationSeconds * 1000\n : scheduled?.durationMs;\n\n if (this.debug) {\n const mode = this.host.config.isLiveStream ? \"LIVE\" : \"VOD\";\n console.log(\n `[CONTINUOUS-FETCH] ${mode} MODE: Target duration=${adBreakDurationMs}ms`\n );\n }\n\n this.timing.failedVastUrls.clear();\n this.timing.temporaryFailureUrls.clear();\n this.timing.consecutiveFailures = 0;\n this.continuousFetchingActive = true;\n this.isShowingPlaceholder = false;\n this.timing.totalAdRequestsInBreak = 0;\n\n if (this.adConfig.podAssignedByPrefetch) {\n this.adConfig.podAssignedByPrefetch = false;\n } else {\n this.adConfig.beginNewAdPod();\n }\n\n const currentMuted = this.host.video.muted;\n const currentVolume = this.host.video.volume;\n this.host.getAdPlayer().updateOriginalMutedState(currentMuted, currentVolume);\n\n this.inAdBreak = true;\n this.timing.adBreakPlayedDurationMs = 0;\n this.timing.currentAdIndex = 0;\n this.timing.totalAdsInBreak = 0;\n this.adPodQueue = [];\n this.showAds = false;\n\n if (\n this.timing.expectedAdBreakDurationMs == null &&\n adBreakDurationMs != null\n ) {\n this.timing.expectedAdBreakDurationMs = adBreakDurationMs;\n }\n\n let firstAdUrl: string | undefined;\n let usePreloadedAd = false;\n let preloadedController: AdController | undefined;\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n firstAdUrl = preloaded.vastUrl;\n preloadedController = preloaded.adController;\n usePreloadedAd = true;\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad from pool (preloaded in advance, ready immediately!)\");\n }\n } else if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {\n this.adRequestQueue = [...this.pendingAdBreak.vastUrls];\n firstAdUrl = this.adRequestQueue.shift();\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Pool empty, using prefetched URLs (${this.adRequestQueue.length + 1} available)`);\n }\n\n this.clearPendingAdBreak();\n } else {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Generating new ad URLs...\");\n }\n\n const firstAdUrlArray = this.host.generateVastUrls(baseVastUrl, 1);\n firstAdUrl = firstAdUrlArray[0];\n this.adRequestQueue = [];\n }\n\n if (!firstAdUrl) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Failed to get first ad URL\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First VAST URL:\", firstAdUrl);\n }\n\n try {\n if (usePreloadedAd && preloadedController) {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedController)) {\n this.timing.rejectLoadedAdForDuration(preloadedController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n\n this.attachImaEventListeners();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Using preloaded ad, resuming and starting playback immediately (no request delay!)\");\n }\n\n preloadedController.resume();\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n }\n if (!this.preloadPool.isLoopRunning) {\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n await preloadedController.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n preloadedController.setAdVolume(adVolume);\n } else {\n const adPlayer = this.host.getAdPlayer();\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n await adPlayer.requestAds(firstAdUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: firstAdUrl, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad request successful, starting playback\");\n }\n\n if (!this.timing.ensureLoadedAdFitsBudget(adPlayer)) {\n this.timing.rejectLoadedAdForDuration(adPlayer);\n this.recreateAdController();\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.startPreloadPool(baseVastUrl, []);\n }\n\n await adPlayer.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n adPlayer.setAdVolume(adVolume);\n }\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] First ad request failed:\", error);\n }\n\n if (!usePreloadedAd) {\n const fallbackPreloaded = this.preloadPool.getPreloadedAd();\n if (fallbackPreloaded) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad failed, using preloaded fallback\");\n }\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(fallbackPreloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(fallbackPreloaded.adController);\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(fallbackPreloaded.adController);\n\n this.timing.consecutiveFailures = 0;\n this.startContinuousFetching(baseVastUrl);\n\n if (!this.preloadPool.active) {\n this.preloadPool.active = true;\n this.preloadPool.preloadPoolLoop(baseVastUrl);\n }\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n const adVolume = currentMuted ? 0 : currentVolume;\n ap.setAdVolume(adVolume);\n\n return;\n } catch (fallbackError) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded fallback also failed:\", fallbackError);\n }\n }\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(firstAdUrl, Date.now());\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had temporary error (no-fill) - will try alternatives\");\n }\n } else {\n this.timing.failedVastUrls.add(firstAdUrl);\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] First ad had permanent error - URL blacklisted\");\n }\n }\n this.timing.consecutiveFailures++;\n\n this.startContinuousFetching(baseVastUrl);\n await this.tryNextAvailableAdWithRateLimit();\n }\n }\n\n private swapToPreloadedAdPlayer(preloadedController: AdController): void {\n const adPlayer = this.host.getAdPlayer();\n const preservedMuted = adPlayer.getOriginalMutedState();\n const preservedVolume = adPlayer.getOriginalVolume();\n adPlayer.destroy();\n this.host.video.muted = true;\n this.host.setAdPlayer(preloadedController);\n this.attachImaEventListeners();\n preloadedController.updateOriginalMutedState(preservedMuted, preservedVolume);\n preloadedController.resume();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Continuous fetching\n // ───────────────────────────────────────────────────────────────\n\n private startContinuousFetching(baseVastUrl: string): void {\n if (!this.continuousFetchingActive) {\n return;\n }\n\n if (this.continuousFetchLoopRunning) {\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start\");\n }\n return;\n }\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Starting continuous ad fetching loop\");\n }\n\n this.continuousFetchLoopRunning = true;\n this.continuousFetchLoop(baseVastUrl);\n }\n\n private async continuousFetchLoop(baseVastUrl: string): Promise<void> {\n const epoch = this.timing.adBreakEpoch;\n while (\n this.continuousFetchingActive &&\n this.inAdBreak &&\n epoch === this.timing.adBreakEpoch\n ) {\n const remaining = Math.min(\n this.timing.getWallClockRemainingAdMs(),\n this.timing.getDurationBudgetRemainingMs()\n );\n\n if (remaining <= this.timing.getMinRemainingMsToStartAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough ad break time left (wall=${this.timing.getWallClockRemainingAdMs()}ms, budget=${this.timing.getDurationBudgetRemainingMs()}ms), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation\");\n }\n break;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), stopping URL generation`);\n }\n break;\n }\n\n if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Maximum ad requests reached (${this.timing.maxTotalAdRequestsPerBreak}), stopping`);\n }\n break;\n }\n\n const maxQueueSize = 5;\n if (this.adRequestQueue.length >= maxQueueSize) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] URL queue full (${this.adRequestQueue.length}), waiting...`);\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n continue;\n }\n\n const newAdUrl = this.host.generateVastUrls(baseVastUrl, 1)[0];\n\n if (!newAdUrl || this.timing.failedVastUrls.has(newAdUrl) || this.timing.isUrlInCooldown(newAdUrl)) {\n await new Promise(resolve => setTimeout(resolve, 500));\n continue;\n }\n\n if (this.debug) {\n const queuedUrlsPreview = [...this.adRequestQueue, newAdUrl];\n console.log(\n `[CONTINUOUS-FETCH] Queued VAST URL (queue size: ${queuedUrlsPreview.length})`,\n { queuedUrls: queuedUrlsPreview }\n );\n }\n\n this.adRequestQueue.push(newAdUrl);\n\n const generationDelay = this.timing.consecutiveFailures > 0\n ? Math.min(1000 * Math.pow(2, this.timing.consecutiveFailures), 5000)\n : 500;\n await new Promise(resolve => setTimeout(resolve, generationDelay));\n }\n\n this.continuousFetchLoopRunning = false;\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] URL generation loop ended (queued: ${this.adRequestQueue.length})`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n }\n\n stopContinuousFetching(): void {\n this.continuousFetchingActive = false;\n this.continuousFetchLoopRunning = false;\n\n this.placeholder.hide();\n\n if (this.debug) {\n console.log(\"[CONTINUOUS-FETCH] Stopping continuous ad fetching\");\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad iteration\n // ───────────────────────────────────────────────────────────────\n\n async tryNextAvailableAdWithRateLimit(): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const epoch = this.timing.adBreakEpoch;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n const backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);\n const backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);\n const effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);\n\n const timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;\n if (timeSinceLastRequest < effectiveMinInterval) {\n const waitTime = effectiveMinInterval - timeSinceLastRequest;\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Rate limiting: waiting ${waitTime}ms before next request (backoff: ${this.timing.consecutiveFailures} failures)`);\n }\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n\n if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {\n return;\n }\n\n return this.tryNextAvailableAd(0);\n }\n\n private async tryNextAvailableAd(retryCount: number = 0): Promise<void> {\n if (!this.inAdBreak) {\n return;\n }\n\n const remaining = this.timing.getRemainingAdMs();\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Not enough time remaining (${remaining}ms) to start another ad, ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) {\n console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully\");\n }\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Too many consecutive failures (${this.timing.consecutiveFailures}), ending ad break`);\n }\n this.handleAdPodComplete();\n return;\n }\n\n this.timing.cleanupTemporaryFailures();\n\n const preloaded = this.preloadPool.getPreloadedAd();\n if (preloaded) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Using preloaded ad from pool`);\n }\n\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: preloaded.vastUrl, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloaded.adController)) {\n this.timing.rejectLoadedAdForDuration(preloaded.adController);\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n this.swapToPreloadedAdPlayer(preloaded.adController);\n\n const ap = this.host.getAdPlayer();\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n\n this.timing.consecutiveFailures = 0;\n return;\n } catch (error) {\n if (this.debug) {\n console.warn(\"[CONTINUOUS-FETCH] Preloaded ad failed to play:\", error);\n }\n }\n }\n\n while (this.adRequestQueue.length > 0) {\n const nextAdUrl = this.adRequestQueue.shift();\n\n if (!nextAdUrl) continue;\n\n if (this.timing.failedVastUrls.has(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...\");\n continue;\n }\n\n if (this.timing.isUrlInCooldown(nextAdUrl)) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...\");\n continue;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (${this.timing.currentAdIndex + 1}, ${this.adRequestQueue.length} remaining in queue)`);\n }\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad request failed:\", errorMessage);\n\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n\n const maxRetries = 3;\n if (this.continuousFetchingActive && retryCount < maxRetries && remaining > 2000) {\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (${retryCount + 1}/${maxRetries})`);\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n await this.tryNextAvailableAd(retryCount + 1);\n return;\n }\n\n if (!this.isShowingPlaceholder && remaining > 1000) {\n this.showPlaceholderAndWaitForAds();\n } else {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] No more ads available, ending ad break\");\n this.handleAdPodComplete();\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Single ad playback\n // ───────────────────────────────────────────────────────────────\n\n async playSingleAd(vastTagUrl: string): Promise<void> {\n const adPlayer = this.host.getAdPlayer();\n if (adPlayer.isAdPlaying()) return;\n\n if (this.timing.failedVastUrls.has(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping permanently-failed VAST URL:\", vastTagUrl);\n throw new Error(\"VAST URL permanently failed\");\n }\n\n if (this.timing.isUrlInCooldown(vastTagUrl)) {\n if (this.debug) console.warn(\"[AD-ERROR] Skipping URL in cooldown (recent no-fill):\", vastTagUrl);\n throw new Error(\"VAST URL in cooldown after no-fill\");\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.warn(\"[AD-ERROR] Too many consecutive failures, not requesting more ads\");\n throw new Error(\"Too many consecutive failures\");\n }\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.warn(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request\");\n throw new Error(\"GAM in cooldown\");\n }\n\n this.recreateAdController();\n\n const requestToken = ++this.timing.adRequestTokenCounter;\n this.timing.activeAdRequestToken = requestToken;\n this.timing.startAdRequestWatchdog(requestToken);\n\n try {\n await this.timing.enforceGlobalRateLimit();\n this.timing.lastAdRequestTime = Date.now();\n const ap = this.host.getAdPlayer();\n await ap.requestAds(vastTagUrl);\n sendAdLoadedTracking(\n this.host.config.licenseKey,\n { source: \"hls\", vastUrl: vastTagUrl, timestamp: new Date().toISOString() },\n this.analyticsContext\n ).catch(() => {});\n\n this.timing.clearAdRequestWatchdog();\n\n if (this.timing.activeAdRequestToken !== requestToken) return;\n\n if (!this.timing.ensureLoadedAdFitsBudget(ap)) {\n this.timing.rejectLoadedAdForDuration(ap);\n this.recreateAdController();\n throw new Error(\"ad_duration_exceeds_budget\");\n }\n\n try {\n this.timing.startAdFailsafeTimer(requestToken);\n await ap.play();\n this.timing.markAdStarted();\n\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n\n ap.setAdVolume(getAdAudioVolume(ap));\n this.timing.consecutiveFailures = 0;\n this.timing.temporaryFailureUrls.delete(vastTagUrl);\n } catch (playError) {\n if (this.debug) console.error(\"[AD-ERROR] Failed to play ad:\", playError);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Play failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw playError;\n }\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {\n this.timing.scheduleAdStopAtBreakBoundary();\n }\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(playError as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary play error - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent play error - URL blacklisted\");\n }\n\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw playError;\n }\n } catch (error) {\n const errorMessage = (error as Error)?.message || \"\";\n if (this.debug) console.error(\"[AD-ERROR] Ad request failed:\", errorMessage);\n\n const preloadedFallback = this.preloadPool.getPreloadedAd();\n if (preloadedFallback) {\n if (this.debug) console.log(\"[AD-ERROR] Request failed, trying preloaded fallback ad\");\n try {\n if (!this.timing.ensureLoadedAdFitsBudget(preloadedFallback.adController)) {\n this.timing.rejectLoadedAdForDuration(preloadedFallback.adController);\n throw error;\n }\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n this.swapToPreloadedAdPlayer(preloadedFallback.adController);\n this.timing.consecutiveFailures = 0;\n const fbAp = this.host.getAdPlayer();\n await fbAp.play();\n this.timing.markAdStarted();\n fbAp.setAdVolume(getAdAudioVolume(fbAp));\n return;\n } catch (fallbackError) {\n if (this.debug) console.warn(\"[AD-ERROR] Preloaded fallback also failed:\", fallbackError);\n }\n }\n\n if (this.timing.isTemporaryAdError(error as Error)) {\n this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());\n if (this.debug) console.log(\"[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown\");\n } else {\n this.timing.failedVastUrls.add(vastTagUrl);\n if (this.debug) console.log(\"[AD-ERROR] Permanent error - URL blacklisted:\", errorMessage);\n }\n\n this.timing.clearAdRequestWatchdog();\n this.timing.clearAdFailsafeTimer();\n if (this.timing.activeAdRequestToken === requestToken) {\n this.timing.activeAdRequestToken = null;\n }\n throw error;\n }\n }\n\n // ───────────────────────────────────────────────────────────────\n // Placeholder wait\n // ───────────────────────────────────────────────────────────────\n\n private async showPlaceholderAndWaitForAds(): Promise<void> {\n const remaining = this.timing.getRemainingAdMs();\n const waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);\n\n if (this.timing.isGamInCooldown()) {\n if (this.debug) console.log(\"[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait\");\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures\");\n this.handleAdPodComplete();\n return;\n }\n\n if (waitTime < 1000) {\n this.handleAdPodComplete();\n return;\n }\n\n if (this.debug) {\n console.log(`[CONTINUOUS-FETCH] Showing placeholder for ${waitTime}ms while waiting for ad URLs`);\n }\n\n this.isShowingPlaceholder = true;\n this.host.getAdPlayer().showPlaceholder();\n\n const checkInterval = 300;\n const maxChecks = Math.floor(waitTime / checkInterval);\n\n for (let i = 0; i < maxChecks; i++) {\n await new Promise(resolve => setTimeout(resolve, checkInterval));\n\n if (!this.inAdBreak) return;\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Too many failures during placeholder wait\");\n break;\n }\n\n if (!this.timing.hasTimeToStartAnotherAd()) {\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break\");\n break;\n }\n\n while (this.adRequestQueue.length > 0) {\n if (!this.timing.hasTimeToStartAnotherAd()) break;\n\n const nextAdUrl = this.adRequestQueue.shift();\n if (!nextAdUrl) continue;\n if (this.timing.failedVastUrls.has(nextAdUrl)) continue;\n if (this.timing.isUrlInCooldown(nextAdUrl)) continue;\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n\n try {\n await this.playSingleAd(nextAdUrl);\n this.timing.consecutiveFailures = 0;\n } catch (error) {\n const errorMessage = (error as Error).message;\n if (errorMessage.includes(\"ad_duration_exceeds_budget\")) {\n await this.tryNextAvailableAdWithRateLimit();\n return;\n }\n if (!errorMessage.includes(\"permanently failed\") && !errorMessage.includes(\"in cooldown\")) {\n this.timing.consecutiveFailures++;\n }\n await this.tryNextAvailableAdWithRateLimit();\n }\n return;\n }\n }\n\n if (this.debug) console.log(\"[CONTINUOUS-FETCH] Placeholder timeout, ending ad break\");\n\n this.isShowingPlaceholder = false;\n this.host.getAdPlayer().hidePlaceholder();\n this.handleAdPodComplete();\n }\n\n // ───────────────────────────────────────────────────────────────\n // Ad break completion\n // ───────────────────────────────────────────────────────────────\n\n handleAdPodComplete(): void {\n if (this.debug) {\n console.log(\"[StormcloudVideoPlayer] Ad pod complete - cleaning up\");\n }\n\n this.timing.resetForBreakEnd();\n\n this.stopContinuousFetching();\n this.preloadPool.stop();\n this.clearPendingAdBreak();\n\n if (this.isShowingPlaceholder) {\n this.host.getAdPlayer().hidePlaceholder();\n this.isShowingPlaceholder = false;\n }\n\n this.adRequestQueue = [];\n\n this.inAdBreak = false;\n this.adDetectSentForCurrentBreak = false;\n this.cueManager.activeScte35BreakKey = undefined;\n this.cueManager.scheduledScte35BreakKey = undefined;\n this.adPodQueue = [];\n this.showAds = false;\n\n this.host.getAdPlayer().stop().catch(() => {});\n\n const restoredMuted = this.host.getAdPlayer().getOriginalMutedState();\n const restoredVolume = this.host.getAdPlayer().getOriginalVolume();\n\n if (this.host.video.muted !== restoredMuted) {\n this.host.video.muted = restoredMuted;\n }\n if (Math.abs(this.host.video.volume - restoredVolume) > 0.01) {\n this.host.video.volume = restoredVolume;\n }\n\n if (this.host.shouldContinueLiveStreamDuringAds()) {\n const liveSyncPos = this.host.getLiveSyncPosition();\n if (liveSyncPos != null && liveSyncPos > this.host.video.currentTime) {\n if (this.debug) {\n console.log(\n `[StormcloudVideoPlayer] Live break end — snapping to live edge: ${this.host.video.currentTime.toFixed(2)}s → ${liveSyncPos.toFixed(2)}s`\n );\n }\n this.host.video.currentTime = liveSyncPos;\n }\n\n if (this.host.video.paused) {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video paused in live mode after ads, resuming playback\");\n this.host.video.play()?.catch(() => {});\n } else {\n if (this.debug) console.log(\"[StormcloudVideoPlayer] Content video already playing in live mode after ads\");\n }\n } else if (this.host.video.paused) {\n this.host.video.play()?.catch(() => {});\n }\n }\n\n handleAdFailure(): void {\n this.timing.consecutiveFailures++;\n this.timing.recordGamNoFill();\n const remaining = this.timing.getRemainingAdMs();\n\n if (this.debug) {\n console.log(\n `[CONTINUOUS-FETCH] Ad failure: remaining=${remaining}ms, queued ads=${this.adRequestQueue.length}, consecutiveFailures=${this.timing.consecutiveFailures}`,\n this.adRequestQueue.length > 0 ? { queuedUrls: [...this.adRequestQueue] } : {}\n );\n }\n\n if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {\n if (this.debug) console.log(`[CONTINUOUS-FETCH] Max consecutive failures reached (${this.timing.consecutiveFailures}), ending ad break gracefully`);\n this.handleAdPodComplete();\n return;\n }\n\n if (this.timing.hasTimeToStartAnotherAd()) {\n this.tryNextAvailableAdWithRateLimit();\n } else {\n if (this.debug) console.log(\"[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:\", this.timing.failedVastUrls.size);\n this.handleAdPodComplete();\n }\n }\n}\n","export const MQTT_CA_CERT_FILE = \"src/certs/emqxsl-ca.crt\";\n\nexport type MQTTConfig = {\n enabled: boolean;\n brokerAddress: string;\n brokerPort: number;\n wsPort: number;\n username: string;\n password: string;\n topicPrefix: string;\n qos: 0 | 1 | 2;\n brokerUrl?: string;\n};\n\nexport const DEFAULT_MQTT_CONFIG: MQTTConfig = {\n enabled: true,\n brokerAddress: \"vecbae77.ala.us-east-1.emqxsl.com\",\n brokerPort: 8883,\n wsPort: 8084,\n username: \"for-sonifi\",\n password: \"sonifi-mqtt\",\n topicPrefix: \"adstorm/players\",\n qos: 1,\n};\n\nexport const mqttConfig: MQTTConfig = { ...DEFAULT_MQTT_CONFIG };\n\nexport function applyMQTTConfig(overrides: Partial<MQTTConfig>): void {\n Object.assign(mqttConfig, overrides);\n}\n\nexport function isMQTTEnabled(): boolean {\n return mqttConfig.enabled;\n}\n\nexport function buildMQTTBrokerUrl(): string {\n if (mqttConfig.brokerUrl) return mqttConfig.brokerUrl;\n return `wss://${mqttConfig.brokerAddress}:${mqttConfig.wsPort}/mqtt`;\n}\n\nexport function buildPlayerTopic(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\"\n): string {\n return `${mqttConfig.topicPrefix}/${licenseKey}/${channel}`;\n}\n","import mqtt from \"mqtt\";\nimport type { MqttClient } from \"mqtt\";\nimport {\n applyMQTTConfig,\n buildMQTTBrokerUrl,\n isMQTTEnabled,\n mqttConfig,\n} from \"./mqttConfig\";\nimport type { MQTTConfig } from \"./mqttConfig\";\n\nconst LOG = \"[StormcloudVideoPlayer][MQTT]\";\n\nexport type MQTTStatus = \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n\nlet client: MqttClient | null = null;\nlet status: MQTTStatus = \"disconnected\";\n\nexport function getMQTTStatus(): MQTTStatus {\n return status;\n}\n\nexport function isMQTTConnected(): boolean {\n return status === \"connected\" && client !== null && client.connected;\n}\n\nexport function isMQTTConfigured(): boolean {\n return isMQTTEnabled();\n}\n\nexport function configureMQTT(overrides: Partial<MQTTConfig>): void {\n applyMQTTConfig(overrides);\n disconnectMQTT();\n}\n\nexport function initMQTTClient(): void {\n if (client || !isMQTTEnabled()) return;\n\n const url = buildMQTTBrokerUrl();\n status = \"connecting\";\n\n const clientId = `stormcloud-vp-${Math.random().toString(36).slice(2, 9)}`;\n\n try {\n client = mqtt.connect(url, {\n clientId,\n username: mqttConfig.username,\n password: mqttConfig.password,\n keepalive: 60,\n clean: true,\n reconnectPeriod: 5000,\n connectTimeout: 10_000,\n queueQoSZero: false,\n });\n } catch (err) {\n status = \"error\";\n console.warn(`${LOG} connect() threw:`, err);\n return;\n }\n\n client.on(\"connect\", () => {\n status = \"connected\";\n console.info(`${LOG} connected to ${url}`);\n });\n\n client.on(\"reconnect\", () => {\n status = \"connecting\";\n console.info(`${LOG} reconnecting…`);\n });\n\n client.on(\"offline\", () => {\n status = \"disconnected\";\n console.warn(`${LOG} offline`);\n });\n\n client.on(\"error\", (err) => {\n status = \"error\";\n console.warn(`${LOG} error:`, err.message);\n });\n\n client.on(\"close\", () => {\n if (status === \"connected\") {\n status = \"disconnected\";\n }\n });\n}\n\nexport function ensureMQTTClient(): void {\n if (isMQTTEnabled() && !client) {\n initMQTTClient();\n }\n}\n\nexport function publishMQTT(\n topic: string,\n payload: Record<string, unknown>\n): boolean {\n if (!isMQTTEnabled()) {\n return false;\n }\n\n ensureMQTTClient();\n\n if (!client) {\n return false;\n }\n\n try {\n client.publish(topic, JSON.stringify(payload), { qos: mqttConfig.qos });\n return true;\n } catch (err) {\n console.warn(`${LOG} publish failed on ${topic}:`, err);\n return false;\n }\n}\n\nexport function disconnectMQTT(): void {\n if (client) {\n client.end(true);\n client = null;\n status = \"disconnected\";\n }\n}\n","export interface VastEnvironmentSignals {\n isCtv: boolean;\n contentUrl?: string;\n appId?: string;\n appName?: string;\n sessionId?: string;\n deviceId?: string;\n deviceIdType?: string;\n limitAdTracking?: boolean;\n deviceTypeHint?: number;\n}\n\nconst AIRY_ANDROID_APP_ID = \"com.freeairytv.android\";\nconst AIRY_WEBOS_APP_ID = \"com.freeairytv.webos\";\nconst AIRY_TIZEN_APP_ID = \"com.freeairytv.samsung\";\nconst AIRY_ROKU_APP_ID = \"com.freeairytv.roku\";\nconst AIRY_APP_NAME = \"AiryTV Movies & TV\";\nconst AIRY_DEFAULT_CONTENT_URL = \"https://live.airy.tv\";\nconst CTV_SESSION_STORAGE_KEY = \"stormcloud.ctv.sid\";\nexport const PLAYER_ID_STORAGE_KEY = \"stormcloud.player.id\";\n\nconst LG_TEST_APP_ID = \"com.hulu.plus\";\nconst LG_TEST_APP_NAME = \"Hulu\";\nconst LG_TEST_CONTENT_URL = \"https://www.hulu.com/live-tv\";\n\nlet _lgTestDeviceId: string | undefined;\nfunction getLgTestDeviceId(): string {\n if (!_lgTestDeviceId) _lgTestDeviceId = createUuid();\n return _lgTestDeviceId;\n}\n\nfunction isLgWebOS(): boolean {\n if (typeof navigator === \"undefined\") return false;\n return /Web0S|webOS|LG Browser|LGSTB|LGE/i.test(navigator.userAgent);\n}\n\nfunction getDefaultAppId(): string {\n if (typeof navigator === \"undefined\") return AIRY_ANDROID_APP_ID;\n const ua = navigator.userAgent;\n if (/Web0S|webOS|LG Browser|LGSTB|LGE/i.test(ua)) return AIRY_WEBOS_APP_ID;\n if (/Tizen|Samsung/i.test(ua)) return AIRY_TIZEN_APP_ID;\n if (/Roku/i.test(ua)) return AIRY_ROKU_APP_ID;\n return AIRY_ANDROID_APP_ID;\n}\n\nconst DEVICE_ID_STORAGE_KEYS = [\n \"rdid\",\n \"ifa\",\n \"advertisingId\",\n \"advertising_id\",\n \"deviceAdvertisingId\",\n \"aaid\",\n \"adid\",\n \"rida\",\n \"tifa\",\n \"lgudid\",\n];\n\nconst ANDROID_ID_TYPES = new Set([\"aaid\", \"adid\"]);\n\nexport function resolveVastEnvironmentSignals(isCtv: boolean): VastEnvironmentSignals {\n const bridgeSignals = readNativeBridgeSignals();\n const platformDevice = readPlatformNativeDeviceId();\n const lg = isCtv && isLgWebOS();\n\n const deviceId =\n bridgeSignals.deviceId ||\n readStoredDeviceId() ||\n platformDevice.deviceId ||\n (lg && platformDevice.limitAdTracking !== true ? getLgTestDeviceId() : undefined);\n const deviceIdType =\n bridgeSignals.deviceIdType ||\n readStoredString(\"deviceIdType\") ||\n readStoredString(\"idtype\") ||\n platformDevice.deviceIdType ||\n inferDeviceIdType() ||\n (lg ? \"lgudid\" : undefined);\n const platformLat = bridgeSignals.deviceId\n ? bridgeSignals.limitAdTracking\n : platformDevice.limitAdTracking;\n const limitAdTracking =\n deviceId != null\n ? platformLat ?? readStoredLimitAdTracking() ?? false\n : undefined;\n\n if (isCtv) {\n return {\n isCtv: true,\n contentUrl:\n bridgeSignals.contentUrl ||\n readStoredString(\"contentUrl\") ||\n (lg ? LG_TEST_CONTENT_URL : AIRY_DEFAULT_CONTENT_URL),\n appId:\n bridgeSignals.appId ||\n readStoredString(\"appId\") ||\n readStoredString(\"msid\") ||\n (lg ? LG_TEST_APP_ID : getDefaultAppId()),\n appName:\n bridgeSignals.appName ||\n readStoredString(\"appName\") ||\n readStoredString(\"an\") ||\n (lg ? LG_TEST_APP_NAME : AIRY_APP_NAME),\n sessionId: getOrCreateCtvSessionId(),\n ...(deviceId ? { deviceId } : {}),\n ...(deviceIdType ? { deviceIdType } : {}),\n ...(limitAdTracking != null ? { limitAdTracking } : {}),\n deviceTypeHint: 5,\n };\n }\n\n return {\n isCtv: false,\n ...(deviceId ? { deviceId } : {}),\n ...(deviceIdType ? { deviceIdType } : {}),\n ...(limitAdTracking != null ? { limitAdTracking } : {}),\n };\n}\n\nexport function inferDeviceIdType(): string | undefined {\n if (typeof navigator === \"undefined\") {\n return undefined;\n }\n\n const ua = navigator.userAgent;\n if (/Roku/i.test(ua)) return \"rida\";\n if (/Tizen|Samsung/i.test(ua)) return \"tifa\";\n if (/AppleTV|Apple TV/i.test(ua)) return \"tvOS\";\n if (/AFT|Fire TV|Amazon/i.test(ua)) return \"afai\";\n if (/Web0S|webOS|LG Browser|LGSTB|LGE/i.test(ua)) return \"lgudid\";\n if (/Android|Google TV/i.test(ua)) return \"aaid\";\n if (/iPhone|iPad|iPod/i.test(ua)) return \"idfa\";\n return undefined;\n}\n\nexport function isEquivalentDeviceIdType(\n tagType: string | undefined,\n runtimeType: string | undefined\n): boolean {\n if (!tagType || !runtimeType) return false;\n const tag = tagType.toLowerCase();\n const runtime = runtimeType.toLowerCase();\n if (tag === runtime) return true;\n return ANDROID_ID_TYPES.has(tag) && ANDROID_ID_TYPES.has(runtime);\n}\n\nexport function resolveNativeDeviceId(): string | undefined {\n const bridgeSignals = readNativeBridgeSignals();\n const platformDevice = readPlatformNativeDeviceId();\n const deviceId =\n bridgeSignals.deviceId ||\n readStoredDeviceId() ||\n platformDevice.deviceId;\n\n if (!deviceId || isMacroPlaceholder(deviceId) || isZeroedAdId(deviceId)) {\n return undefined;\n }\n\n return deviceId;\n}\n\nexport function getOrCreateStoredUuid(storageKey: string): string | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const existing = readStoredString(storageKey);\n if (existing) {\n return existing;\n }\n\n const id = createUuid();\n try {\n window.localStorage?.setItem(storageKey, id);\n } catch {}\n return id;\n}\n\nfunction getOrCreateCtvSessionId(): string {\n const existing = readStoredString(CTV_SESSION_STORAGE_KEY);\n if (existing) {\n return existing;\n }\n\n const sessionId = createUuid();\n try {\n window.localStorage?.setItem(CTV_SESSION_STORAGE_KEY, sessionId);\n } catch {}\n return sessionId;\n}\n\nfunction createUuid(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (char) => {\n const value = Math.floor(Math.random() * 16);\n const nibble = char === \"x\" ? value : (value & 0x3) | 0x8;\n return nibble.toString(16);\n });\n}\n\nfunction readPlatformNativeDeviceId(): {\n deviceId?: string;\n deviceIdType?: string;\n limitAdTracking?: boolean;\n} {\n if (typeof window === \"undefined\") return {};\n\n try {\n const adinfo = (window as any).webapis?.adinfo;\n if (adinfo) {\n const tifa: unknown =\n typeof adinfo.getTIFA === \"function\" ? adinfo.getTIFA() : adinfo.tifa;\n if (typeof tifa === \"string\" && tifa && !isMacroPlaceholder(tifa)) {\n const lat: unknown =\n typeof adinfo.isLATEnabled === \"function\"\n ? adinfo.isLATEnabled()\n : undefined;\n return {\n deviceId: tifa,\n deviceIdType: \"tifa\",\n ...(typeof lat === \"boolean\" ? { limitAdTracking: lat } : {}),\n };\n }\n }\n } catch {}\n\n try {\n const webOSDev = (window as any).webOSDev;\n if (webOSDev) {\n const lgudid: unknown =\n typeof webOSDev.LGUDID === \"function\"\n ? webOSDev.LGUDID()\n : webOSDev.lgudid ?? webOSDev.LGUDID;\n if (typeof lgudid === \"string\" && lgudid) {\n if (isZeroedAdId(lgudid)) {\n return { deviceIdType: \"lgudid\", limitAdTracking: true };\n }\n if (!isMacroPlaceholder(lgudid)) {\n return { deviceId: lgudid, deviceIdType: \"lgudid\", limitAdTracking: false };\n }\n }\n }\n } catch {}\n\n try {\n const roku = (window as any).Roku;\n if (roku) {\n const rida: unknown =\n typeof roku.getPublisherUniqueId === \"function\"\n ? roku.getPublisherUniqueId()\n : roku.rida;\n if (typeof rida === \"string\" && rida && !isMacroPlaceholder(rida)) {\n return { deviceId: rida, deviceIdType: \"rida\", limitAdTracking: false };\n }\n }\n } catch {}\n\n return {};\n}\n\nconst ZEROED_AD_ID_PATTERNS: ReadonlySet<string> = new Set([\n \"38400000-8cf0-11bd-b23e-10b96e40000d\",\n \"00000000-0000-0000-0000-000000000000\",\n]);\n\nfunction isMacroPlaceholder(value: string): boolean {\n const t = value.trim();\n return !t ||\n /^(\\[[^\\]]*\\]|\\{[^}]*\\}|%%[^%]*%%)$/.test(t) ||\n /^(unknown|null|undefined|none|n\\/a|\\$\\{[^}]+\\})$/i.test(t) ||\n ZEROED_AD_ID_PATTERNS.has(t.toLowerCase());\n}\n\nfunction isZeroedAdId(value: string): boolean {\n return ZEROED_AD_ID_PATTERNS.has(value.trim().toLowerCase());\n}\n\nfunction readNativeBridgeSignals(): {\n contentUrl?: string;\n appId?: string;\n appName?: string;\n deviceId?: string;\n deviceIdType?: string;\n limitAdTracking?: boolean;\n} {\n if (typeof window === \"undefined\") {\n return {};\n }\n\n const candidates = [\n (window as any).__STORMCLOUD_CTV_AD_INFO__,\n (window as any).__STORMCLOUD_CTV__,\n (window as any).stormcloudCtv,\n (window as any).AiryTV,\n (window as any).Android,\n (window as any).webOS,\n (window as any).tizen,\n (window as any).amazon,\n ].filter(Boolean);\n\n for (const source of candidates) {\n const contentUrl =\n readBridgeValue(source, [\"contentUrl\", \"url\", \"videoUrl\", \"canonicalUrl\"]) ||\n undefined;\n const appId =\n readBridgeValue(source, [\"appId\", \"msid\", \"applicationId\", \"packageName\"]) ||\n undefined;\n const appName =\n readBridgeValue(source, [\"appName\", \"an\", \"applicationName\"]) || undefined;\n const deviceId =\n readBridgeValue(source, [\n \"rdid\",\n \"ifa\",\n \"advertisingId\",\n \"adId\",\n \"deviceId\",\n \"lgudid\",\n \"LGUDID\",\n \"tifa\",\n \"rida\",\n \"afai\",\n \"aaid\",\n ]) || undefined;\n\n if (!contentUrl && !deviceId && !appId && !appName) continue;\n\n const deviceIdType =\n readBridgeValue(source, [\n \"idtype\",\n \"deviceIdType\",\n \"advertisingIdType\",\n \"idType\",\n ]) || inferDeviceIdType();\n const limitAdTracking = readBridgeBoolean(source, [\n \"is_lat\",\n \"limitAdTracking\",\n \"limitedAdTracking\",\n \"lat\",\n ]);\n\n return {\n ...(contentUrl ? { contentUrl } : {}),\n ...(appId ? { appId } : {}),\n ...(appName ? { appName } : {}),\n ...(deviceId ? { deviceId } : {}),\n ...(deviceId && deviceIdType ? { deviceIdType } : {}),\n ...(deviceId && limitAdTracking != null ? { limitAdTracking } : {}),\n };\n }\n\n return {};\n}\n\nfunction readBridgeValue(source: any, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = source?.[key];\n if (typeof value === \"string\" && value) {\n return value;\n }\n if (typeof value === \"function\") {\n try {\n const result = value.call(source);\n if (typeof result === \"string\" && result) {\n return result;\n }\n } catch {}\n }\n }\n return undefined;\n}\n\nfunction readBridgeBoolean(source: any, keys: string[]): boolean | undefined {\n for (const key of keys) {\n const value = source?.[key];\n const normalized = normalizeBoolean(value);\n if (normalized != null) {\n return normalized;\n }\n if (typeof value === \"function\") {\n try {\n const result = normalizeBoolean(value.call(source));\n if (result != null) {\n return result;\n }\n } catch {}\n }\n }\n return undefined;\n}\n\nfunction readStoredDeviceId(): string | undefined {\n for (const key of DEVICE_ID_STORAGE_KEYS) {\n const value = readStoredString(key);\n if (value) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction readStoredString(key: string): string | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n try {\n const value = window.localStorage?.getItem(key);\n return value || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readStoredLimitAdTracking(): boolean | undefined {\n return normalizeBoolean(\n readStoredString(\"limitAdTracking\") ||\n readStoredString(\"limitedAdTracking\") ||\n readStoredString(\"is_lat\")\n );\n}\n\nfunction normalizeBoolean(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n const normalized = value.toLowerCase();\n if (normalized === \"1\" || normalized === \"true\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"0\" || normalized === \"false\" || normalized === \"no\") {\n return false;\n }\n }\n return undefined;\n}\n","import type {\n ClientInfo,\n AdDetectInfo,\n AdLoadedInfo,\n AdImpressionInfo,\n PlayerAnalyticsContext,\n StormcloudVideoPlayerConfig,\n} from \"../types\";\n\nimport { buildPlayerTopic, isMQTTEnabled } from \"./mqttConfig\";\nimport { ensureMQTTClient, publishMQTT } from \"./mqttClient\";\nimport {\n getOrCreateStoredUuid,\n PLAYER_ID_STORAGE_KEY,\n resolveNativeDeviceId,\n} from \"./vastEnvironmentSignals\";\n\nlet cachedBrowserId: string | null = null;\n\nexport function buildAnalyticsContext(\n config: Pick<StormcloudVideoPlayerConfig, \"debugAdTiming\" | \"isLiveStream\">\n): PlayerAnalyticsContext {\n const context: PlayerAnalyticsContext = {};\n if (config.debugAdTiming) {\n context.debugAdTiming = true;\n }\n if (config.isLiveStream !== undefined) {\n context.inputStreamType = config.isLiveStream ? \"live\" : \"vod\";\n }\n return context;\n}\n\nexport function getClientInfo(): ClientInfo {\n const ua = navigator.userAgent;\n const platform = navigator.platform;\n const vendor = navigator.vendor || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 0;\n const memory = (navigator as any).deviceMemory || null;\n const hardwareConcurrency = navigator.hardwareConcurrency || 1;\n\n const screenInfo = {\n width: screen?.width,\n height: screen?.height,\n availWidth: screen?.availWidth,\n availHeight: screen?.availHeight,\n orientation: (screen?.orientation as any)?.type || \"\",\n pixelDepth: screen?.pixelDepth,\n };\n\n let deviceType: \"tv\" | \"mobile\" | \"tablet\" | \"desktop\" = \"desktop\";\n let brand = \"Unknown\";\n let os = \"Unknown\";\n let model = \"\";\n let isSmartTV = false;\n let isAndroid = false;\n let isWebView = false;\n let isWebApp = false;\n\n if (ua.includes(\"Web0S\")) {\n brand = \"LG\";\n os = \"webOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n const webosMatch = ua.match(/Web0S\\/([^\\s]+)/);\n model = webosMatch ? `webOS ${webosMatch[1]}` : \"webOS TV\";\n } else if (ua.includes(\"Tizen\")) {\n brand = \"Samsung\";\n os = \"Tizen\";\n isSmartTV = true;\n deviceType = \"tv\";\n const tizenMatch = ua.match(/Tizen\\/([^\\s]+)/);\n const tvMatch = ua.match(/(?:Smart-TV|SMART-TV|TV)/i) ? \"Smart TV\" : \"\";\n model = tizenMatch\n ? `Tizen ${tizenMatch[1]} ${tvMatch}`.trim()\n : \"Tizen TV\";\n } else if (ua.includes(\"Philips\")) {\n brand = \"Philips\";\n os = \"Saphi\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"Sharp\") || ua.includes(\"AQUOS\")) {\n brand = \"Sharp\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"Sony\") || vendor.includes(\"Sony\"))\n ) {\n brand = \"Sony\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (\n ua.includes(\"Android\") &&\n (ua.includes(\"NetCast\") || ua.includes(\"LG\"))\n ) {\n brand = \"LG\";\n os = \"Android TV\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\" Roku\") || ua.includes(\"Roku/\")) {\n brand = \"Roku\";\n os = \"Roku OS\";\n isSmartTV = true;\n deviceType = \"tv\";\n } else if (ua.includes(\"AppleTV\")) {\n brand = \"Apple\";\n os = \"tvOS\";\n isSmartTV = true;\n deviceType = \"tv\";\n }\n\n if (ua.includes(\"Android\")) {\n isAndroid = true;\n os = \"Android\";\n deviceType = /Mobile/.test(ua) ? \"mobile\" : \"tablet\";\n\n if (\n ua.includes(\"Android\") &&\n (maxTouchPoints === 0 ||\n ua.includes(\"Google TV\") ||\n ua.includes(\"XiaoMi\"))\n ) {\n deviceType = \"tv\";\n isSmartTV = true;\n brand = brand === \"Unknown\" ? \"Android TV\" : brand;\n }\n\n const androidModelMatch = ua.match(/\\(([^)]*Android[^)]*)\\)/);\n if (androidModelMatch && androidModelMatch[1]) {\n model = androidModelMatch[1];\n }\n }\n\n if (/iPad|iPhone|iPod/.test(ua)) {\n os = \"iOS\";\n deviceType = \"mobile\";\n brand = \"Apple\";\n if (navigator.maxTouchPoints > 1 && /iPad/.test(ua)) {\n deviceType = \"tablet\";\n }\n }\n\n if (!isAndroid && !isSmartTV && !/Mobile/.test(ua)) {\n if (ua.includes(\"Windows\")) {\n os = \"Windows\";\n deviceType = \"desktop\";\n } else if (ua.includes(\"Mac\") && !/iPhone/.test(ua)) {\n os = \"macOS\";\n deviceType = \"desktop\";\n if (maxTouchPoints > 1) deviceType = \"tablet\";\n } else if (ua.includes(\"Linux\")) {\n os = \"Linux\";\n deviceType = \"desktop\";\n }\n }\n\n if (brand === \"Unknown\") {\n if (vendor.includes(\"Google\") || ua.includes(\"Chrome\")) brand = \"Google\";\n if (vendor.includes(\"Apple\")) brand = \"Apple\";\n if (vendor.includes(\"Samsung\") || ua.includes(\"SM-\")) brand = \"Samsung\";\n }\n\n isWebView = /wv|WebView|Linux; U;/.test(ua);\n\n if (window?.outerHeight === 0 && window?.outerWidth === 0) {\n isWebView = true;\n }\n\n isWebApp =\n window.matchMedia(\"(display-mode: standalone)\").matches ||\n (window.navigator as any).standalone === true ||\n window.screen?.orientation?.angle !== undefined;\n\n return {\n brand,\n os,\n model: model || ua.substring(0, 50) + \"...\",\n deviceType,\n isSmartTV,\n isAndroid,\n isWebView,\n isWebApp,\n domain: window.location.hostname,\n origin: window.location.origin,\n path: window.location.pathname,\n userAgent: ua,\n vendor,\n platform,\n screen: screenInfo,\n hardwareConcurrency,\n deviceMemory: memory,\n maxTouchPoints,\n language: navigator.language,\n languages: navigator.languages?.join(\",\") || \"\",\n cookieEnabled: navigator.cookieEnabled,\n doNotTrack: navigator.doNotTrack || \"\",\n referrer: document.referrer,\n visibilityState: document.visibilityState,\n };\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n if (typeof crypto !== \"undefined\" && crypto.subtle?.digest) {\n try {\n await crypto.subtle.digest(\"SHA-256\", new Uint8Array([1, 2, 3]));\n\n let encodedData: BufferSource;\n if (typeof TextEncoder !== \"undefined\") {\n encodedData = new TextEncoder().encode(input);\n } else {\n const utf8 = unescape(encodeURIComponent(input));\n const buffer = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n buffer[i] = utf8.charCodeAt(i);\n }\n encodedData = buffer;\n }\n\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encodedData);\n return Array.from(new Uint8Array(hashBuffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n } catch {\n console.warn(\n \"[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash\"\n );\n }\n }\n\n let hash = 0;\n for (let i = 0; i < input.length; i++) {\n const char = input.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n const fallbackHash = Math.abs(hash).toString(16).padStart(8, \"0\");\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Math.random().toString(16).substring(2, 14).padStart(12, \"0\");\n\n return (fallbackHash + timestamp + random).padEnd(64, \"0\");\n}\n\nfunction resolvePlayerIdentitySeed(clientInfo: ClientInfo): string {\n const nativeDeviceId = resolveNativeDeviceId();\n if (nativeDeviceId) {\n return `device:${nativeDeviceId}`;\n }\n\n const persistedId = getOrCreateStoredUuid(PLAYER_ID_STORAGE_KEY);\n if (persistedId) {\n return `persisted:${persistedId}`;\n }\n\n return `fingerprint:${JSON.stringify(clientInfo)}`;\n}\n\nexport async function getBrowserID(clientInfo: ClientInfo): Promise<string> {\n if (cachedBrowserId) {\n return cachedBrowserId;\n }\n\n cachedBrowserId = await sha256Hex(resolvePlayerIdentitySeed(clientInfo));\n return cachedBrowserId;\n}\n\ntype PlayerMetricFlags = {\n adLoaded?: boolean;\n adDetect?: boolean;\n captureAt?: string;\n};\n\nfunction canPublish(licenseKey: string | undefined): licenseKey is string {\n return Boolean(isMQTTEnabled() && licenseKey);\n}\n\nasync function buildPlayerMetricEvent(\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<Record<string, unknown>> {\n const clientInfo = getClientInfo();\n\n const debugAdTiming = !!context.debugAdTiming;\n if (debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] clientInfo: \", JSON.stringify(clientInfo, null, 2));\n }\n\n const playerId = await getBrowserID(clientInfo);\n\n if (debugAdTiming) {\n console.log(\"[StormcloudVideoPlayer] playerId: \", playerId);\n }\n\n const captureAt = flags.captureAt ?? new Date().toISOString();\n\n return {\n player_id: playerId,\n device_type: clientInfo.deviceType,\n os: clientInfo.os.toLowerCase(),\n ad_loaded: flags.adLoaded ?? false,\n ad_detect: flags.adDetect ?? false,\n capture_at: captureAt,\n ...(context.inputStreamType\n ? { input_stream_type: context.inputStreamType }\n : {}),\n };\n}\n\nfunction publishTracking(\n licenseKey: string,\n channel: \"metrics\" | \"impressions\" | \"heartbeat\",\n body: Record<string, unknown>\n): void {\n ensureMQTTClient();\n publishMQTT(buildPlayerTopic(licenseKey, channel), body);\n}\n\nexport async function sendInitialTracking(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n adLoaded: false,\n adDetect: false,\n });\n\n publishTracking(licenseKey, \"metrics\", {\n events: [metricEvent],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending initial tracking data:\",\n error\n );\n }\n}\n\nexport async function sendAdDetectTracking(\n licenseKey: string | undefined,\n adDetectInfo: AdDetectInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adDetect: true,\n captureAt: adDetectInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad detect tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdLoadedTracking(\n licenseKey: string | undefined,\n adLoadedInfo: AdLoadedInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n try {\n await sendHeartbeat(licenseKey, context, {\n adLoaded: true,\n captureAt: adLoadedInfo.timestamp,\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad loaded tracking:\",\n error\n );\n }\n}\n\nexport async function sendAdImpressionTracking(\n licenseKey: string | undefined,\n adImpressionInfo: AdImpressionInfo,\n context: PlayerAnalyticsContext = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const metricEvent = await buildPlayerMetricEvent(context, {\n captureAt: adImpressionInfo.timestamp,\n });\n\n publishTracking(licenseKey, \"heartbeat\", metricEvent);\n publishTracking(licenseKey, \"impressions\", {\n events: [\n {\n player_id: metricEvent.player_id,\n ad_played_count: 1,\n ad_url: adImpressionInfo.adUrl,\n capture_at: adImpressionInfo.timestamp,\n },\n ],\n });\n } catch (error) {\n console.error(\n \"[StormcloudVideoPlayer] Error sending ad impression tracking:\",\n error\n );\n }\n}\n\nexport async function sendHeartbeat(\n licenseKey?: string,\n context: PlayerAnalyticsContext = {},\n flags: PlayerMetricFlags = {}\n): Promise<void> {\n if (!canPublish(licenseKey)) return;\n\n try {\n const heartbeatData = await buildPlayerMetricEvent(context, flags);\n publishTracking(licenseKey, \"heartbeat\", heartbeatData);\n } catch (error) {\n console.error(\"[StormcloudVideoPlayer] Error sending heartbeat:\", error);\n }\n}\n","import type { AdController } from \"../types\";\n\nexport function getAdAudioVolume(adPlayer: AdController): number {\n return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();\n}\n\nexport function toggleMute(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (adPlayer.isAdPlaying()) {\n const newMutedState = !adPlayer.getOriginalMutedState();\n const restoreVolume = adPlayer.getOriginalVolume() || 1;\n\n adPlayer.updateOriginalMutedState(newMutedState, video.volume);\n adPlayer.setAdVolume(newMutedState ? 0 : restoreVolume);\n\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:\",\n newMutedState\n );\n }\n } else {\n video.muted = !video.muted;\n adPlayer.updateOriginalMutedState(video.muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Muted:\", video.muted);\n }\n }\n}\n\nexport function toggleFullscreen(\n video: HTMLVideoElement,\n debug: boolean\n): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!document.fullscreenElement) {\n const container = video.parentElement;\n if (!container) {\n reject(new Error(\"No parent container found for fullscreen\"));\n return;\n }\n container\n .requestFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Entered fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\"[StormcloudVideoPlayer] Fullscreen error:\", err);\n }\n reject(err);\n });\n } else {\n document\n .exitFullscreen()\n .then(() => {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Exited fullscreen\");\n }\n resolve();\n })\n .catch((err) => {\n if (debug) {\n console.error(\n \"[StormcloudVideoPlayer] Exit fullscreen error:\",\n err\n );\n }\n reject(err);\n });\n }\n });\n}\n\nexport function isMuted(\n video: HTMLVideoElement,\n adPlayer: AdController\n): boolean {\n if (adPlayer.isAdPlaying()) {\n return adPlayer.getOriginalMutedState();\n }\n return video.muted;\n}\n\nexport function setMuted(\n video: HTMLVideoElement,\n adPlayer: AdController,\n muted: boolean,\n debug: boolean\n): void {\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying && muted === video.muted) {\n if (debug) {\n console.log(\n \"[StormcloudVideoPlayer] setMuted reflective update during ad ignored\",\n { muted }\n );\n }\n return;\n }\n\n video.muted = muted;\n\n if (adPlaying) {\n adPlayer.updateOriginalMutedState(muted, video.volume);\n adPlayer.setAdVolume(muted ? 0 : 1);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted applied during ad\", {\n muted,\n });\n }\n return;\n }\n\n adPlayer.updateOriginalMutedState(muted, video.volume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setMuted called:\", muted);\n }\n}\n\nexport function setVolume(\n video: HTMLVideoElement,\n adPlayer: AdController,\n volume: number,\n debug: boolean\n): void {\n const clampedVolume = Math.max(0, Math.min(1, volume));\n const adPlaying = adPlayer.isAdPlaying();\n\n if (adPlaying) {\n adPlayer.setAdVolume(clampedVolume);\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume applied during ad\", {\n volume: clampedVolume,\n });\n }\n } else {\n video.volume = clampedVolume;\n video.muted = clampedVolume === 0;\n adPlayer.updateOriginalMutedState(clampedVolume === 0, clampedVolume);\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] setVolume called:\", clampedVolume);\n }\n }\n}\n\nexport function getVolume(\n video: HTMLVideoElement,\n adPlayer: AdController\n): number {\n const adPlaying = adPlayer.isAdPlaying();\n if (adPlaying) {\n return adPlayer.getAdVolume();\n }\n return video.volume;\n}\n\nexport function isFullscreen(): boolean {\n return !!document.fullscreenElement;\n}\n\nexport function resizePlayer(\n video: HTMLVideoElement,\n adPlayer: AdController,\n debug: boolean\n): void {\n if (debug) {\n console.log(\"[StormcloudVideoPlayer] Resizing player\");\n }\n\n if (adPlayer && adPlayer.isAdPlaying()) {\n const width = video.clientWidth || 640;\n const height = video.clientHeight || 480;\n\n if (debug) {\n console.log(\n `[StormcloudVideoPlayer] Resizing ads manager to ${width}x${height}`\n );\n }\n\n adPlayer.resize(width, height);\n }\n}\n"]}