stormcloud-video-player 0.7.3 → 0.7.5

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.
@@ -435,185 +435,8 @@ var canPlay = {
435
435
  // src/players/HlsPlayer.tsx
436
436
  var import_react2 = require("react");
437
437
  // src/player/StormcloudVideoPlayer.ts
438
- var import_hls2 = __toESM(require("hls.js"), 1);
438
+ var import_hls = __toESM(require("hls.js"), 1);
439
439
  // src/sdk/vastParser.ts
440
- function isHlsType(type) {
441
- return type === "application/x-mpegURL" || type.includes("m3u8");
442
- }
443
- function isMp4Type(type) {
444
- return type === "video/mp4" || type.includes("mp4");
445
- }
446
- function parseVastXml(xmlString) {
447
- var filter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "all", logPrefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "[VastParser]";
448
- try {
449
- var _xmlDoc_querySelector, _xmlDoc_querySelector1, _xmlDoc_querySelector_textContent, _xmlDoc_querySelector2;
450
- var parser = new DOMParser();
451
- var xmlDoc = parser.parseFromString(xmlString, "text/xml");
452
- var parserError = xmlDoc.querySelector("parsererror");
453
- if (parserError) {
454
- console.error("".concat(logPrefix, " XML parsing error (malformed VAST XML):"), parserError.textContent);
455
- return null;
456
- }
457
- var adElement = xmlDoc.querySelector("Ad");
458
- if (!adElement) {
459
- console.warn("".concat(logPrefix, " No Ad element found in VAST XML"));
460
- return null;
461
- }
462
- var adId = adElement.getAttribute("id") || "unknown";
463
- var title = ((_xmlDoc_querySelector = xmlDoc.querySelector("AdTitle")) === null || _xmlDoc_querySelector === void 0 ? void 0 : _xmlDoc_querySelector.textContent) || "Ad";
464
- var isNoAdAvailable = adId === "empty" || title.toLowerCase().includes("no ad available") || title.toLowerCase() === "no ad available";
465
- var durationText = ((_xmlDoc_querySelector1 = xmlDoc.querySelector("Duration")) === null || _xmlDoc_querySelector1 === void 0 ? void 0 : _xmlDoc_querySelector1.textContent) || "00:00:30";
466
- var durationParts = durationText.split(":");
467
- var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + Math.round(parseFloat(durationParts[2] || "0"));
468
- var mediaFileElements = xmlDoc.querySelectorAll("MediaFile");
469
- var mediaFiles = [];
470
- console.log("".concat(logPrefix, " Found ").concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
471
- mediaFileElements.forEach(function(mf, index) {
472
- var _mf_textContent;
473
- var type = mf.getAttribute("type") || "";
474
- var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
475
- var width = mf.getAttribute("width") || "";
476
- var height = mf.getAttribute("height") || "";
477
- console.log("".concat(logPrefix, " MediaFile ").concat(index, ': type="').concat(type, '", url="').concat(url.substring(0, 80), '...", width="').concat(width, '", height="').concat(height, '"'));
478
- if (!url) {
479
- console.warn("".concat(logPrefix, " MediaFile ").concat(index, " has empty URL"));
480
- return;
481
- }
482
- var isHls = isHlsType(type);
483
- var isMp4 = isMp4Type(type);
484
- var accepted = false;
485
- if (filter === "hls-only") {
486
- accepted = isHls;
487
- } else if (filter === "mp4-first") {
488
- accepted = isMp4 || isHls;
489
- } else {
490
- accepted = true;
491
- }
492
- if (!accepted) {
493
- console.log("".concat(logPrefix, " MediaFile ").concat(index, ' ignored (type="').concat(type, '" not accepted by filter "').concat(filter, '")'));
494
- return;
495
- }
496
- var bitrateAttr = mf.getAttribute("bitrate");
497
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
498
- mediaFiles.push({
499
- url: url,
500
- type: type,
501
- width: parseInt(width || "1920", 10),
502
- height: parseInt(height || "1080", 10),
503
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
504
- });
505
- console.log("".concat(logPrefix, ' Added MediaFile: type="').concat(type, '" url="').concat(url.substring(0, 80), '..."'));
506
- });
507
- if (filter === "mp4-first" && mediaFiles.length > 1) {
508
- mediaFiles.sort(function(a, b) {
509
- var aIsMp4 = isMp4Type(a.type) ? 0 : 1;
510
- var bIsMp4 = isMp4Type(b.type) ? 0 : 1;
511
- return aIsMp4 - bIsMp4;
512
- });
513
- }
514
- if (mediaFiles.length === 0) {
515
- if (isNoAdAvailable) {
516
- console.warn("".concat(logPrefix, " No ads available (VAST response indicates no ads)"));
517
- } else {
518
- console.warn("".concat(logPrefix, " No compatible media files found in VAST XML"));
519
- }
520
- return null;
521
- }
522
- var trackingUrls = {
523
- impression: [],
524
- start: [],
525
- firstQuartile: [],
526
- midpoint: [],
527
- thirdQuartile: [],
528
- complete: [],
529
- mute: [],
530
- unmute: [],
531
- pause: [],
532
- resume: [],
533
- fullscreen: [],
534
- exitFullscreen: [],
535
- skip: [],
536
- error: []
537
- };
538
- xmlDoc.querySelectorAll("Impression").forEach(function(el) {
539
- var _el_textContent;
540
- var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
541
- if (url) trackingUrls.impression.push(url);
542
- });
543
- xmlDoc.querySelectorAll("Tracking").forEach(function(el) {
544
- var _el_textContent;
545
- var event = el.getAttribute("event");
546
- var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
547
- if (event && url) {
548
- var eventKey = event;
549
- if (trackingUrls[eventKey]) {
550
- trackingUrls[eventKey].push(url);
551
- }
552
- }
553
- });
554
- var clickThrough = (_xmlDoc_querySelector2 = xmlDoc.querySelector("ClickThrough")) === null || _xmlDoc_querySelector2 === void 0 ? void 0 : (_xmlDoc_querySelector_textContent = _xmlDoc_querySelector2.textContent) === null || _xmlDoc_querySelector_textContent === void 0 ? void 0 : _xmlDoc_querySelector_textContent.trim();
555
- return {
556
- id: adId,
557
- title: title,
558
- duration: duration,
559
- mediaFiles: mediaFiles,
560
- trackingUrls: trackingUrls,
561
- clickThrough: clickThrough
562
- };
563
- } catch (error) {
564
- console.error("".concat(logPrefix, " Error parsing VAST XML:"), error);
565
- return null;
566
- }
567
- }
568
- function fetchAndParseVastAd(vastTagUrl) {
569
- var filter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "all", logPrefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "[VastParser]";
570
- return _async_to_generator(function() {
571
- var response, vastXml;
572
- return _ts_generator(this, function(_state) {
573
- switch(_state.label){
574
- case 0:
575
- return [
576
- 4,
577
- fetch(vastTagUrl, {
578
- mode: "cors",
579
- credentials: "include",
580
- headers: {
581
- Accept: "application/xml, text/xml, */*"
582
- },
583
- referrerPolicy: "no-referrer-when-downgrade"
584
- })
585
- ];
586
- case 1:
587
- response = _state.sent();
588
- if (!response.ok) {
589
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
590
- }
591
- return [
592
- 4,
593
- response.text()
594
- ];
595
- case 2:
596
- vastXml = _state.sent();
597
- console.log("".concat(logPrefix, " VAST XML received"));
598
- console.log("".concat(logPrefix, " VAST XML content (first 2000 chars):"), vastXml.substring(0, 2e3));
599
- return [
600
- 2,
601
- parseVastXml(vastXml, filter, logPrefix)
602
- ];
603
- }
604
- });
605
- })();
606
- }
607
- function createEmptyTrackingState() {
608
- return {
609
- impression: false,
610
- start: false,
611
- firstQuartile: false,
612
- midpoint: false,
613
- thirdQuartile: false,
614
- complete: false
615
- };
616
- }
617
440
  function firePixelWithRetry(url) {
618
441
  var retries = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 2, delayMs = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 500, logPrefix = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : "[VastParser]";
619
442
  return _async_to_generator(function() {
@@ -736,16 +559,164 @@ function fireTrackingPixels(urls, sessionId) {
736
559
  }
737
560
  });
738
561
  }
739
- // src/sdk/vastManager.ts
740
- var VAST_TAG_URL = "https://pubads.g.doubleclick.net/gampad/ads?iu=/21821455290/Airy-Android&description_url=http%3A%2F%2Fairy.tv&tfcd=0&npa=0&sz=1x1%7C300x250%7C400x300%7C640x480&gdfp_req=1&unviewed_position_start=1&correlator=[placeholder]&vpos=preroll&output=vast&env=vp&vpmute=0&vpa=click";
741
- var DEFAULT_TIMEOUT_MS = 5e3;
742
- var MAX_RETRIES = 3;
743
- var RETRY_BACKOFF_MS = 1500;
744
- function createVastManager() {
745
- var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
746
- var _options_debug;
747
- var initialized = false;
748
- var debug = (_options_debug = options.debug) !== null && _options_debug !== void 0 ? _options_debug : false;
562
+ // src/sdk/adstormPlayer.ts
563
+ var SUPPORTED_VIDEO_EXTENSIONS = [
564
+ ".mp4",
565
+ ".webm",
566
+ ".ogg",
567
+ ".m3u8",
568
+ ".ts"
569
+ ];
570
+ var UNSUPPORTED_VIDEO_EXTENSIONS = [
571
+ ".flv",
572
+ ".f4v",
573
+ ".swf",
574
+ ".wmv",
575
+ ".avi",
576
+ ".mov",
577
+ ".mkv"
578
+ ];
579
+ var REQUEST_TIMEOUT_MS = 5e3;
580
+ var REQUEST_MAX_RETRIES = 3;
581
+ var REQUEST_RETRY_BACKOFF_MS = 1500;
582
+ var AD_LAYER_Z_INDEX = "30";
583
+ var COUNTDOWN_Z_INDEX = "31";
584
+ var STALL_TIMEOUT_MS = 8e3;
585
+ function getFileExtension(url) {
586
+ try {
587
+ var pathname = new URL(url, "http://dummy").pathname;
588
+ var lastDot = pathname.lastIndexOf(".");
589
+ if (lastDot === -1) return "";
590
+ return pathname.slice(lastDot).toLowerCase();
591
+ } catch (unused) {
592
+ var lastDot1 = url.lastIndexOf(".");
593
+ if (lastDot1 === -1) return "";
594
+ var ext = url.slice(lastDot1).split(/[?#]/)[0];
595
+ return (ext || "").toLowerCase();
596
+ }
597
+ }
598
+ function isUnsupportedFormat(url) {
599
+ var ext = getFileExtension(url);
600
+ return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;
601
+ }
602
+ function replaceFlvExtension(url) {
603
+ var ext = getFileExtension(url);
604
+ if (ext === ".flv") {
605
+ return url.replace(/\.flv(\?|$)/i, ".mp4$1");
606
+ }
607
+ return url;
608
+ }
609
+ function isSupportedFormat(url, mimeType) {
610
+ if (isUnsupportedFormat(url)) {
611
+ return false;
612
+ }
613
+ var ext = getFileExtension(url);
614
+ if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {
615
+ return true;
616
+ }
617
+ if (ext === "" || ext === ".") {
618
+ return mimeType.includes("video/mp4") || mimeType.includes("video/webm") || mimeType.includes("m3u8") || mimeType.includes("application/x-mpegurl");
619
+ }
620
+ return false;
621
+ }
622
+ function createAdStormPlayer(contentVideo, options) {
623
+ var licenseKey = options.licenseKey, _options_debug = options.debug, debug = _options_debug === void 0 ? false : _options_debug;
624
+ var adPlaying = false;
625
+ var originalMutedState = false;
626
+ var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
627
+ var listeners = /* @__PURE__ */ new Map();
628
+ var adVideoElement;
629
+ var adContainerEl;
630
+ var adCountdownEl;
631
+ var currentAd;
632
+ var destroyed = false;
633
+ var tornDown = false;
634
+ var continueLiveStreamDuringAds = false;
635
+ var sessionId;
636
+ var adStallTimerId;
637
+ var adCountdownTimerId;
638
+ var adHideTimerId;
639
+ var lastCountdownSecond = -1;
640
+ var adListenersBound = false;
641
+ var parentPositionOverridden = false;
642
+ var adHandlers = {
643
+ timeupdate: function timeupdate() {
644
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
645
+ var progress = adVideoElement.currentTime / currentAd.duration;
646
+ if (progress >= 0.25 && !trackingFired.firstQuartile) {
647
+ trackingFired.firstQuartile = true;
648
+ fireTrackingPixels2(currentAd.trackingUrls.firstQuartile);
649
+ }
650
+ if (progress >= 0.5 && !trackingFired.midpoint) {
651
+ trackingFired.midpoint = true;
652
+ fireTrackingPixels2(currentAd.trackingUrls.midpoint);
653
+ }
654
+ if (progress >= 0.75 && !trackingFired.thirdQuartile) {
655
+ trackingFired.thirdQuartile = true;
656
+ fireTrackingPixels2(currentAd.trackingUrls.thirdQuartile);
657
+ }
658
+ updateAdCountdown();
659
+ },
660
+ playing: function playing() {
661
+ clearAdStallTimer();
662
+ if (!currentAd || trackingFired.start || destroyed || tornDown) return;
663
+ trackingFired.start = true;
664
+ fireTrackingPixels2(currentAd.trackingUrls.start);
665
+ startAdCountdown();
666
+ log("Ad started playing");
667
+ },
668
+ ended: function ended() {
669
+ if (!currentAd || trackingFired.complete || destroyed || tornDown) return;
670
+ trackingFired.complete = true;
671
+ fireTrackingPixels2(currentAd.trackingUrls.complete);
672
+ log("Ad completed");
673
+ handleAdComplete();
674
+ },
675
+ error: function error(e) {
676
+ if (destroyed || tornDown) return;
677
+ console.error("[AdStormPlayer] Ad video error:", e);
678
+ if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);
679
+ handleAdError();
680
+ },
681
+ waiting: function waiting() {
682
+ clearAdStallTimer();
683
+ adStallTimerId = setTimeout(function() {
684
+ adStallTimerId = void 0;
685
+ if (!adPlaying || destroyed || tornDown) return;
686
+ console.warn("[AdStormPlayer] Ad playback stalled too long");
687
+ handleAdError();
688
+ }, STALL_TIMEOUT_MS);
689
+ },
690
+ volumechange: function volumechange() {
691
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
692
+ if (adVideoElement.muted || adVideoElement.volume <= 0) {
693
+ fireTrackingPixels2(currentAd.trackingUrls.mute);
694
+ } else {
695
+ fireTrackingPixels2(currentAd.trackingUrls.unmute);
696
+ }
697
+ },
698
+ pause: function pause() {
699
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
700
+ if (!adVideoElement.ended) {
701
+ fireTrackingPixels2(currentAd.trackingUrls.pause);
702
+ }
703
+ },
704
+ play: function play() {
705
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
706
+ if (adVideoElement.currentTime > 0) {
707
+ fireTrackingPixels2(currentAd.trackingUrls.resume);
708
+ }
709
+ }
710
+ };
711
+ var trackingFired = {
712
+ impression: false,
713
+ start: false,
714
+ firstQuartile: false,
715
+ midpoint: false,
716
+ thirdQuartile: false,
717
+ complete: false
718
+ };
719
+ var preloadSlots = /* @__PURE__ */ new Map();
749
720
  function log() {
750
721
  for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
751
722
  args[_key] = arguments[_key];
@@ -753,58 +724,340 @@ function createVastManager() {
753
724
  if (debug) {
754
725
  var _console;
755
726
  (_console = console).log.apply(_console, [
756
- "[VastManager]"
727
+ "[AdStormPlayer]"
757
728
  ].concat(_to_consumable_array(args)));
758
729
  }
759
730
  }
760
- function warn() {
761
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
762
- args[_key] = arguments[_key];
731
+ function emit(event, payload) {
732
+ var set = listeners.get(event);
733
+ if (!set) return;
734
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
735
+ try {
736
+ for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
737
+ var fn = _step.value;
738
+ try {
739
+ fn(payload);
740
+ } catch (error) {
741
+ console.warn("[AdStormPlayer] Error in event listener for ".concat(event, ":"), error);
742
+ }
743
+ }
744
+ } catch (err) {
745
+ _didIteratorError = true;
746
+ _iteratorError = err;
747
+ } finally{
748
+ try {
749
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
750
+ _iterator.return();
751
+ }
752
+ } finally{
753
+ if (_didIteratorError) {
754
+ throw _iteratorError;
755
+ }
756
+ }
763
757
  }
764
- var _console;
765
- (_console = console).warn.apply(_console, [
766
- "[VastManager]"
767
- ].concat(_to_consumable_array(args)));
768
758
  }
769
- function initialize() {
770
- return _async_to_generator(function() {
771
- return _ts_generator(this, function(_state) {
772
- if (initialized) return [
773
- 2
774
- ];
775
- initialized = true;
776
- log("Initialized, VAST tag URL:", VAST_TAG_URL.split("?")[0]);
777
- return [
778
- 2
779
- ];
759
+ function fireTrackingPixels2(urls) {
760
+ fireTrackingPixels(urls, sessionId, "[AdStormPlayer]");
761
+ }
762
+ function clearAdStallTimer() {
763
+ if (adStallTimerId) {
764
+ clearTimeout(adStallTimerId);
765
+ adStallTimerId = void 0;
766
+ }
767
+ }
768
+ function clearAdCountdownTimer() {
769
+ if (adCountdownTimerId) {
770
+ clearInterval(adCountdownTimerId);
771
+ adCountdownTimerId = void 0;
772
+ }
773
+ lastCountdownSecond = -1;
774
+ }
775
+ function updateAdCountdown() {
776
+ if (!adCountdownEl || !adVideoElement || !currentAd || !adPlaying) return;
777
+ var remainingSec = Math.max(0, Math.ceil((currentAd.duration || 0) - adVideoElement.currentTime));
778
+ if (remainingSec === lastCountdownSecond) return;
779
+ lastCountdownSecond = remainingSec;
780
+ adCountdownEl.textContent = "Ad ".concat(remainingSec, "s");
781
+ emit("ad_countdown", {
782
+ remainingSec: remainingSec,
783
+ durationSec: currentAd.duration,
784
+ currentTimeSec: adVideoElement.currentTime
785
+ });
786
+ }
787
+ function startAdCountdown() {
788
+ clearAdCountdownTimer();
789
+ updateAdCountdown();
790
+ adCountdownTimerId = setInterval(updateAdCountdown, 250);
791
+ }
792
+ function generateSessionId() {
793
+ return "adstorm-".concat(Date.now(), "-").concat(Math.random().toString(36).slice(2, 10));
794
+ }
795
+ function bindAdEventListeners() {
796
+ if (!adVideoElement || adListenersBound) return;
797
+ adVideoElement.addEventListener("timeupdate", adHandlers.timeupdate);
798
+ adVideoElement.addEventListener("playing", adHandlers.playing);
799
+ adVideoElement.addEventListener("ended", adHandlers.ended);
800
+ adVideoElement.addEventListener("error", adHandlers.error);
801
+ adVideoElement.addEventListener("waiting", adHandlers.waiting);
802
+ adVideoElement.addEventListener("volumechange", adHandlers.volumechange);
803
+ adVideoElement.addEventListener("pause", adHandlers.pause);
804
+ adVideoElement.addEventListener("play", adHandlers.play);
805
+ adListenersBound = true;
806
+ }
807
+ function unbindAdEventListeners() {
808
+ if (!adVideoElement || !adListenersBound) return;
809
+ adVideoElement.removeEventListener("timeupdate", adHandlers.timeupdate);
810
+ adVideoElement.removeEventListener("playing", adHandlers.playing);
811
+ adVideoElement.removeEventListener("ended", adHandlers.ended);
812
+ adVideoElement.removeEventListener("error", adHandlers.error);
813
+ adVideoElement.removeEventListener("waiting", adHandlers.waiting);
814
+ adVideoElement.removeEventListener("volumechange", adHandlers.volumechange);
815
+ adVideoElement.removeEventListener("pause", adHandlers.pause);
816
+ adVideoElement.removeEventListener("play", adHandlers.play);
817
+ adListenersBound = false;
818
+ }
819
+ function teardownCurrentPlayback() {
820
+ unbindAdEventListeners();
821
+ clearAdStallTimer();
822
+ clearAdCountdownTimer();
823
+ if (!adVideoElement) return;
824
+ adVideoElement.pause();
825
+ adVideoElement.removeAttribute("src");
826
+ adVideoElement.load();
827
+ }
828
+ function buildVastUrl(durationSeconds, metadata) {
829
+ var baseUrl = "https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(licenseKey, "/pod");
830
+ var defaultMetadata = {
831
+ video: {
832
+ codec: "h264",
833
+ width: contentVideo.videoWidth || 1280,
834
+ height: contentVideo.videoHeight || 720,
835
+ fps: 29.97,
836
+ bitrate: 5e3,
837
+ profile: "high",
838
+ pix_fmt: "yuv420p",
839
+ has_b_frames: 0
840
+ },
841
+ audio: {
842
+ codec: "aac",
843
+ sample_rate: 48e3,
844
+ bitrate: 128
845
+ }
846
+ };
847
+ var finalMetadata = metadata || defaultMetadata;
848
+ var metadataStr = encodeURIComponent(JSON.stringify(finalMetadata));
849
+ return "".concat(baseUrl, "?duration=").concat(Math.ceil(durationSeconds), "&metadata=").concat(metadataStr);
850
+ }
851
+ function parseVastXml(xmlString) {
852
+ var ads = [];
853
+ try {
854
+ var parser = new DOMParser();
855
+ var xmlDoc = parser.parseFromString(xmlString, "text/xml");
856
+ var parserError = xmlDoc.querySelector("parsererror");
857
+ if (parserError) {
858
+ console.error("[AdStormPlayer] XML parsing error:", parserError.textContent);
859
+ return [];
860
+ }
861
+ var adElements = xmlDoc.querySelectorAll("Ad");
862
+ adElements.forEach(function(adElement) {
863
+ var _adElement_querySelector, _adElement_querySelector1, _adElement_querySelector_textContent, _adElement_querySelector2;
864
+ var adId = adElement.getAttribute("id") || "unknown";
865
+ var title = ((_adElement_querySelector = adElement.querySelector("AdTitle")) === null || _adElement_querySelector === void 0 ? void 0 : _adElement_querySelector.textContent) || "Ad";
866
+ var durationText = ((_adElement_querySelector1 = adElement.querySelector("Duration")) === null || _adElement_querySelector1 === void 0 ? void 0 : _adElement_querySelector1.textContent) || "00:00:30";
867
+ var durationParts = durationText.split(":");
868
+ var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + parseFloat(durationParts[2] || "0");
869
+ var mediaFileElements = adElement.querySelectorAll("MediaFile");
870
+ var mediaFiles = [];
871
+ mediaFileElements.forEach(function(mf) {
872
+ var _mf_textContent;
873
+ var type = mf.getAttribute("type") || "";
874
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
875
+ var width = parseInt(mf.getAttribute("width") || "1920", 10);
876
+ var height = parseInt(mf.getAttribute("height") || "1080", 10);
877
+ var bitrate = mf.getAttribute("bitrate") ? parseInt(mf.getAttribute("bitrate"), 10) : void 0;
878
+ if (!url) {
879
+ log("Skipping empty MediaFile URL");
880
+ return;
881
+ }
882
+ var originalUrl = url;
883
+ url = replaceFlvExtension(url);
884
+ if (url !== originalUrl) {
885
+ log("Converted FLV to MP4: ".concat(originalUrl, " -> ").concat(url));
886
+ }
887
+ if (isUnsupportedFormat(url)) {
888
+ var ext = getFileExtension(url);
889
+ log("Skipping unsupported format: ".concat(url, " (extension: ").concat(ext, ", declared type: ").concat(type, ")"));
890
+ return;
891
+ }
892
+ if (isSupportedFormat(url, type)) {
893
+ mediaFiles.push({
894
+ url: url,
895
+ type: type,
896
+ width: width,
897
+ height: height,
898
+ bitrate: bitrate
899
+ });
900
+ log("Found media file: ".concat(url, " (").concat(type, ", ").concat(width, "x").concat(height, ")"));
901
+ } else {
902
+ log("Skipping incompatible media file: ".concat(url, " (type: ").concat(type, ")"));
903
+ }
904
+ });
905
+ if (mediaFiles.length === 0) {
906
+ log("No valid media files found in ad:", adId);
907
+ return;
908
+ }
909
+ var trackingUrls = {
910
+ impression: [],
911
+ start: [],
912
+ firstQuartile: [],
913
+ midpoint: [],
914
+ thirdQuartile: [],
915
+ complete: [],
916
+ mute: [],
917
+ unmute: [],
918
+ pause: [],
919
+ resume: [],
920
+ error: []
921
+ };
922
+ adElement.querySelectorAll("Impression").forEach(function(el) {
923
+ var _el_textContent;
924
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
925
+ if (url) trackingUrls.impression.push(url);
926
+ });
927
+ adElement.querySelectorAll("Tracking").forEach(function(el) {
928
+ var _el_textContent;
929
+ var event = el.getAttribute("event");
930
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
931
+ if (event && url) {
932
+ var eventKey = event;
933
+ if (trackingUrls[eventKey]) {
934
+ trackingUrls[eventKey].push(url);
935
+ }
936
+ }
937
+ });
938
+ var clickThrough = (_adElement_querySelector2 = adElement.querySelector("ClickThrough")) === null || _adElement_querySelector2 === void 0 ? void 0 : (_adElement_querySelector_textContent = _adElement_querySelector2.textContent) === null || _adElement_querySelector_textContent === void 0 ? void 0 : _adElement_querySelector_textContent.trim();
939
+ ads.push({
940
+ id: adId,
941
+ title: title,
942
+ duration: duration,
943
+ mediaFiles: mediaFiles,
944
+ trackingUrls: trackingUrls,
945
+ clickThrough: clickThrough
946
+ });
947
+ log("Parsed ad: ".concat(title, ", duration: ").concat(duration, "s, media files: ").concat(mediaFiles.length));
780
948
  });
781
- })();
949
+ } catch (error) {
950
+ console.error("[AdStormPlayer] Error parsing VAST XML:", error);
951
+ }
952
+ return ads;
953
+ }
954
+ function selectBestMediaFile(mediaFiles) {
955
+ if (mediaFiles.length === 0) return null;
956
+ if (mediaFiles.length === 1) return mediaFiles[0];
957
+ var mp4Files = mediaFiles.filter(function(mf) {
958
+ return mf.type.includes("video/mp4");
959
+ });
960
+ var candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;
961
+ var targetWidth = contentVideo.videoWidth || 1280;
962
+ var targetHeight = contentVideo.videoHeight || 720;
963
+ candidates.sort(function(a, b) {
964
+ var diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);
965
+ var diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);
966
+ return diffA - diffB;
967
+ });
968
+ return candidates[0] || null;
969
+ }
970
+ function createAdVideoElement() {
971
+ var video = document.createElement("video");
972
+ video.style.position = "absolute";
973
+ video.style.left = "0";
974
+ video.style.top = "0";
975
+ video.style.width = "100%";
976
+ video.style.height = "100%";
977
+ video.style.objectFit = "contain";
978
+ video.style.backgroundColor = "#000";
979
+ video.style.zIndex = "1";
980
+ video.playsInline = true;
981
+ video.preload = "auto";
982
+ video.muted = originalMutedState;
983
+ video.volume = originalMutedState ? 0 : originalVolume;
984
+ return video;
985
+ }
986
+ function setAdPlayingFlag(isPlaying) {
987
+ if (isPlaying) {
988
+ contentVideo.dataset.stormcloudAdPlaying = "true";
989
+ } else {
990
+ delete contentVideo.dataset.stormcloudAdPlaying;
991
+ }
992
+ }
993
+ function setupAdEventListeners() {
994
+ bindAdEventListeners();
995
+ }
996
+ function handleAdComplete() {
997
+ if (destroyed || tornDown) return;
998
+ log("Handling ad completion");
999
+ adPlaying = false;
1000
+ setAdPlayingFlag(false);
1001
+ clearAdStallTimer();
1002
+ clearAdCountdownTimer();
1003
+ if (adContainerEl) {
1004
+ adContainerEl.style.opacity = "0";
1005
+ adHideTimerId = setTimeout(function() {
1006
+ if (adContainerEl) {
1007
+ adContainerEl.style.display = "none";
1008
+ adContainerEl.style.pointerEvents = "none";
1009
+ }
1010
+ }, 300);
1011
+ }
1012
+ contentVideo.style.visibility = "visible";
1013
+ contentVideo.style.opacity = "1";
1014
+ contentVideo.muted = originalMutedState;
1015
+ contentVideo.volume = originalVolume;
1016
+ currentAd = void 0;
1017
+ emit("content_resume");
1018
+ emit("all_ads_completed");
1019
+ }
1020
+ function handleAdError() {
1021
+ if (destroyed || tornDown) return;
1022
+ log("Handling ad error");
1023
+ if (!adPlaying) return;
1024
+ adPlaying = false;
1025
+ setAdPlayingFlag(false);
1026
+ clearAdStallTimer();
1027
+ clearAdCountdownTimer();
1028
+ contentVideo.muted = originalMutedState;
1029
+ contentVideo.volume = originalVolume;
1030
+ contentVideo.style.visibility = "visible";
1031
+ contentVideo.style.opacity = "1";
1032
+ if (adContainerEl) {
1033
+ adContainerEl.style.display = "none";
1034
+ adContainerEl.style.pointerEvents = "none";
1035
+ }
1036
+ currentAd = void 0;
1037
+ emit("ad_error");
1038
+ emit("content_resume");
782
1039
  }
783
- function requestBids(_context) {
1040
+ function fetchVastOnce(durationSeconds) {
784
1041
  return _async_to_generator(function() {
785
- var correlator, url, controller, timeoutId, _ref, _ref1, _vastAd_mediaFiles_, _vastAd_mediaFiles_1, fetchOptions, response, vastXml, vastAd, bid, error;
1042
+ var vastUrl, controller, timeoutId, requestInit, response, xmlText;
786
1043
  return _ts_generator(this, function(_state) {
787
1044
  switch(_state.label){
788
1045
  case 0:
789
- if (!initialized) {
790
- throw new Error("VastManager not initialized. Call initialize() first.");
791
- }
792
- correlator = Math.floor(Math.random() * 1e12).toString();
793
- url = VAST_TAG_URL.replace("[placeholder]", correlator);
794
- log("Fetching VAST tag, correlator:", correlator);
1046
+ vastUrl = buildVastUrl(durationSeconds);
1047
+ log("Fetching VAST from:", vastUrl);
795
1048
  controller = typeof AbortController !== "undefined" ? new AbortController() : null;
796
1049
  timeoutId = setTimeout(function() {
797
1050
  return controller === null || controller === void 0 ? void 0 : controller.abort();
798
- }, DEFAULT_TIMEOUT_MS);
1051
+ }, REQUEST_TIMEOUT_MS);
799
1052
  _state.label = 1;
800
1053
  case 1:
801
1054
  _state.trys.push([
802
1055
  1,
803
- 4,
804
1056
  ,
1057
+ 4,
805
1058
  5
806
1059
  ]);
807
- fetchOptions = {
1060
+ requestInit = {
808
1061
  method: "GET",
809
1062
  mode: "cors",
810
1063
  credentials: "omit",
@@ -813,62 +1066,34 @@ function createVastManager() {
813
1066
  },
814
1067
  referrerPolicy: "no-referrer-when-downgrade"
815
1068
  };
816
- if (controller) fetchOptions.signal = controller.signal;
1069
+ if (controller) {
1070
+ requestInit.signal = controller.signal;
1071
+ }
817
1072
  return [
818
1073
  4,
819
- fetch(url, fetchOptions)
1074
+ fetch(vastUrl, requestInit)
820
1075
  ];
821
1076
  case 2:
822
1077
  response = _state.sent();
823
- clearTimeout(timeoutId);
824
1078
  if (!response.ok) {
825
- throw new Error("VAST request returned HTTP ".concat(response.status));
1079
+ throw new Error("Failed to fetch VAST: ".concat(response.status, " ").concat(response.statusText));
826
1080
  }
827
1081
  return [
828
1082
  4,
829
1083
  response.text()
830
1084
  ];
831
1085
  case 3:
832
- vastXml = _state.sent();
833
- log("VAST XML received, length:", vastXml.length);
834
- vastAd = parseVastXml(vastXml, "mp4-first", "[VastManager]");
835
- if (!vastAd) {
836
- log("VAST parsed but no usable ad found");
837
- return [
838
- 2,
839
- []
840
- ];
841
- }
842
- log("Ad parsed: id=".concat(vastAd.id, ", duration=").concat(vastAd.duration, "s, mediaFiles=").concat(vastAd.mediaFiles.length));
843
- bid = {
844
- bidder: "vast-direct",
845
- cpm: 0,
846
- vastXml: vastXml,
847
- width: (_ref = (_vastAd_mediaFiles_ = vastAd.mediaFiles[0]) === null || _vastAd_mediaFiles_ === void 0 ? void 0 : _vastAd_mediaFiles_.width) !== null && _ref !== void 0 ? _ref : 0,
848
- height: (_ref1 = (_vastAd_mediaFiles_1 = vastAd.mediaFiles[0]) === null || _vastAd_mediaFiles_1 === void 0 ? void 0 : _vastAd_mediaFiles_1.height) !== null && _ref1 !== void 0 ? _ref1 : 0,
849
- adId: vastAd.id,
850
- impId: correlator,
851
- creativeId: vastAd.id,
852
- currency: "USD",
853
- durationSec: vastAd.duration
854
- };
1086
+ xmlText = _state.sent();
1087
+ log("VAST response received, length:", xmlText.length);
855
1088
  return [
856
1089
  2,
857
- [
858
- bid
859
- ]
1090
+ parseVastXml(xmlText)
860
1091
  ];
861
1092
  case 4:
862
- error = _state.sent();
863
1093
  clearTimeout(timeoutId);
864
- if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") {
865
- warn("VAST request timed out after ".concat(DEFAULT_TIMEOUT_MS, "ms"));
866
- return [
867
- 2,
868
- []
869
- ];
870
- }
871
- throw error;
1094
+ return [
1095
+ 7
1096
+ ];
872
1097
  case 5:
873
1098
  return [
874
1099
  2
@@ -877,14 +1102,14 @@ function createVastManager() {
877
1102
  });
878
1103
  })();
879
1104
  }
880
- function requestBidsUntilResponse(context) {
1105
+ function fetchVast(durationSeconds) {
881
1106
  return _async_to_generator(function() {
882
1107
  var _loop, lastError, attempt, _ret;
883
1108
  return _ts_generator(this, function(_state) {
884
1109
  switch(_state.label){
885
1110
  case 0:
886
1111
  _loop = function(attempt) {
887
- var bids, err, delay;
1112
+ var ads, error, delay;
888
1113
  return _ts_generator(this, function(_state) {
889
1114
  switch(_state.label){
890
1115
  case 0:
@@ -896,39 +1121,39 @@ function createVastManager() {
896
1121
  ]);
897
1122
  return [
898
1123
  4,
899
- requestBids(context)
1124
+ fetchVastOnce(durationSeconds)
900
1125
  ];
901
1126
  case 1:
902
- bids = _state.sent();
903
- if (bids.length > 0) {
904
- log("requestBidsUntilResponse: got ".concat(bids.length, " ad(s) on attempt ").concat(attempt));
905
- return [
906
- 2,
907
- {
908
- v: bids
909
- }
910
- ];
911
- }
912
- log("requestBidsUntilResponse: no ads on attempt ".concat(attempt, "/").concat(MAX_RETRIES));
1127
+ ads = _state.sent();
1128
+ if (ads.length > 0) return [
1129
+ 2,
1130
+ {
1131
+ v: ads
1132
+ }
1133
+ ];
1134
+ log("No ad returned from VAST on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
913
1135
  return [
914
1136
  3,
915
1137
  3
916
1138
  ];
917
1139
  case 2:
918
- err = _state.sent();
919
- lastError = err;
920
- warn("requestBidsUntilResponse: attempt ".concat(attempt, "/").concat(MAX_RETRIES, " failed:"), err);
1140
+ error = _state.sent();
1141
+ lastError = error;
1142
+ if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") {
1143
+ console.warn("[AdStormPlayer] VAST request timed out (".concat(REQUEST_TIMEOUT_MS, "ms), attempt ").concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
1144
+ } else {
1145
+ console.warn("[AdStormPlayer] VAST request failed on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES, ":"), error);
1146
+ }
921
1147
  return [
922
1148
  3,
923
1149
  3
924
1150
  ];
925
1151
  case 3:
926
- if (!(attempt < MAX_RETRIES)) return [
1152
+ if (!(attempt < REQUEST_MAX_RETRIES)) return [
927
1153
  3,
928
1154
  5
929
1155
  ];
930
- delay = RETRY_BACKOFF_MS * attempt;
931
- log("requestBidsUntilResponse: waiting ".concat(delay, "ms before retry"));
1156
+ delay = REQUEST_RETRY_BACKOFF_MS * attempt;
932
1157
  return [
933
1158
  4,
934
1159
  new Promise(function(resolve) {
@@ -945,13 +1170,10 @@ function createVastManager() {
945
1170
  }
946
1171
  });
947
1172
  };
948
- if (!initialized) {
949
- throw new Error("VastManager not initialized. Call initialize() first.");
950
- }
951
1173
  attempt = 1;
952
1174
  _state.label = 1;
953
1175
  case 1:
954
- if (!(attempt <= MAX_RETRIES)) return [
1176
+ if (!(attempt <= REQUEST_MAX_RETRIES)) return [
955
1177
  3,
956
1178
  4
957
1179
  ];
@@ -973,7 +1195,9 @@ function createVastManager() {
973
1195
  1
974
1196
  ];
975
1197
  case 4:
976
- if (_instanceof(lastError, Error)) throw lastError;
1198
+ if (_instanceof(lastError, Error)) {
1199
+ throw lastError;
1200
+ }
977
1201
  return [
978
1202
  2,
979
1203
  []
@@ -982,946 +1206,468 @@ function createVastManager() {
982
1206
  });
983
1207
  })();
984
1208
  }
985
- function destroy() {
986
- initialized = false;
987
- log("Destroyed");
988
- }
989
- return {
990
- initialize: initialize,
991
- requestBids: requestBids,
992
- requestBidsUntilResponse: requestBidsUntilResponse,
993
- destroy: destroy,
994
- get isInitialized () {
995
- return initialized;
996
- }
997
- };
998
- }
999
- // src/sdk/vastAdLayer.ts
1000
- var import_hls = __toESM(require("hls.js"), 1);
1001
- var LOG = "[VastAdLayer]";
1002
- function resolveBidToVastAd(winner, logPrefix) {
1003
- if (winner.vastXml) {
1004
- var ad = parseVastXml(winner.vastXml, "mp4-first", logPrefix);
1005
- return Promise.resolve(ad);
1006
- }
1007
- if (winner.vastUrl) {
1008
- return fetchAndParseVastAd(winner.vastUrl, "mp4-first", logPrefix);
1009
- }
1010
- return Promise.resolve(null);
1011
- }
1012
- function createVastAdLayer(contentVideo, options) {
1013
- var _ref, _ref1, _ref2, _ref3, _ref4;
1014
- var adPlaying = false;
1015
- var originalMutedState = false;
1016
- var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
1017
- var listeners = /* @__PURE__ */ new Map();
1018
- var mainHlsInstance = options === null || options === void 0 ? void 0 : options.mainHlsInstance;
1019
- var continueLiveStreamDuringAds = (_ref = options === null || options === void 0 ? void 0 : options.continueLiveStreamDuringAds) !== null && _ref !== void 0 ? _ref : false;
1020
- var smartTVMode = (_ref1 = options === null || options === void 0 ? void 0 : options.smartTVMode) !== null && _ref1 !== void 0 ? _ref1 : false;
1021
- var singleElementMode = (_ref2 = options === null || options === void 0 ? void 0 : options.singleElementMode) !== null && _ref2 !== void 0 ? _ref2 : false;
1022
- var forceMP4Ads = (_ref3 = options === null || options === void 0 ? void 0 : options.forceMP4Ads) !== null && _ref3 !== void 0 ? _ref3 : smartTVMode || singleElementMode;
1023
- var debug = (_ref4 = options === null || options === void 0 ? void 0 : options.debug) !== null && _ref4 !== void 0 ? _ref4 : false;
1024
- var adVideoElement;
1025
- var adHls;
1026
- var adContainerEl;
1027
- var currentAd;
1028
- var sessionId;
1029
- var destroyed = false;
1030
- var tornDown = false;
1031
- var trackingFired = createEmptyTrackingState();
1032
- var adStallTimerId;
1033
- var currentAdEventHandlers;
1034
- var preloadSlots = /* @__PURE__ */ new Map();
1035
- function emit(event, payload) {
1036
- var set = listeners.get(event);
1037
- if (!set) return;
1038
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1039
- try {
1040
- for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1041
- var fn = _step.value;
1042
- try {
1043
- fn(payload);
1044
- } catch (error) {
1045
- console.warn("".concat(LOG, " Error in event listener for ").concat(event, ":"), error);
1046
- }
1047
- }
1048
- } catch (err) {
1049
- _didIteratorError = true;
1050
- _iteratorError = err;
1051
- } finally{
1052
- try {
1053
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1054
- _iterator.return();
1055
- }
1056
- } finally{
1057
- if (_didIteratorError) {
1058
- throw _iteratorError;
1059
- }
1060
- }
1061
- }
1062
- }
1063
- function generateSessionId() {
1064
- return "session-".concat(Date.now(), "-").concat(Math.random().toString(36).substr(2, 9));
1065
- }
1066
- function fireTrackingPixels2(urls) {
1067
- fireTrackingPixels(urls, sessionId, LOG);
1068
- }
1069
- function getMainStreamQuality() {
1070
- if (!(mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.levels)) return null;
1071
- var currentLevel = mainHlsInstance.currentLevel;
1072
- if (currentLevel === -1 || !mainHlsInstance.levels[currentLevel]) {
1073
- var autoLevel = mainHlsInstance.loadLevel;
1074
- if (autoLevel !== -1 && mainHlsInstance.levels[autoLevel]) {
1075
- var level2 = mainHlsInstance.levels[autoLevel];
1076
- return {
1077
- width: level2.width || 1920,
1078
- height: level2.height || 1080,
1079
- bitrate: level2.bitrate || 5e6
1080
- };
1081
- }
1082
- return null;
1083
- }
1084
- var level = mainHlsInstance.levels[currentLevel];
1085
- return {
1086
- width: level.width || 1920,
1087
- height: level.height || 1080,
1088
- bitrate: level.bitrate || 5e6
1089
- };
1090
- }
1091
- function selectBestMediaFile(mediaFiles) {
1092
- var _ref;
1093
- var _scoredFiles_;
1094
- if (mediaFiles.length === 0) throw new Error("No media files available");
1095
- var candidates = mediaFiles;
1096
- if (forceMP4Ads) {
1097
- var mp4Only = candidates.filter(function(f) {
1098
- return !isHlsMediaFile(f);
1099
- });
1100
- if (mp4Only.length > 0) {
1101
- candidates = mp4Only;
1102
- if (debug) console.log("".concat(LOG, " forceMP4Ads: filtered to ").concat(mp4Only.length, " MP4-only file(s)"));
1103
- } else if (debug) {
1104
- console.warn("".concat(LOG, " forceMP4Ads: no MP4 files available, falling back to all media files"));
1105
- }
1106
- } else {
1107
- var mp4Only1 = candidates.filter(function(f) {
1108
- return !isHlsMediaFile(f);
1109
- });
1110
- if (mp4Only1.length > 0) {
1111
- candidates = mp4Only1;
1112
- if (debug) console.log("".concat(LOG, " Preferring ").concat(mp4Only1.length, " MP4 file(s) over HLS (mp4-first)"));
1113
- }
1114
- }
1115
- var firstFile = candidates[0];
1116
- if (candidates.length === 1) return firstFile;
1117
- var mainQuality = getMainStreamQuality();
1118
- if (!mainQuality) {
1119
- if (debug) console.log("".concat(LOG, " No main stream quality info, using first media file"));
1120
- return firstFile;
1121
- }
1122
- var scoredFiles = candidates.map(function(file) {
1123
- var widthDiff = Math.abs(file.width - mainQuality.width);
1124
- var heightDiff = Math.abs(file.height - mainQuality.height);
1125
- var resolutionDiff = widthDiff + heightDiff;
1126
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
1127
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
1128
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
1129
- return {
1130
- file: file,
1131
- score: score
1132
- };
1133
- });
1134
- scoredFiles.sort(function(a, b) {
1135
- return a.score - b.score;
1136
- });
1137
- return (_ref = (_scoredFiles_ = scoredFiles[0]) === null || _scoredFiles_ === void 0 ? void 0 : _scoredFiles_.file) !== null && _ref !== void 0 ? _ref : firstFile;
1138
- }
1139
- function isHlsMediaFile(file) {
1140
- return file.type === "application/x-mpegURL" || file.type.includes("m3u8");
1141
- }
1142
- function createAdVideoElement() {
1143
- var video = document.createElement("video");
1144
- video.style.position = "absolute";
1145
- video.style.left = "0";
1146
- video.style.top = "0";
1147
- video.style.width = "100%";
1148
- video.style.height = "100%";
1149
- video.style.objectFit = "contain";
1150
- video.style.backgroundColor = "#000";
1151
- video.playsInline = true;
1152
- video.muted = false;
1153
- video.volume = 1;
1154
- return video;
1155
- }
1156
- function clearAdStallTimer() {
1157
- if (adStallTimerId != null) {
1158
- clearTimeout(adStallTimerId);
1159
- adStallTimerId = void 0;
1160
- }
1161
- }
1162
- function removeAdEventListeners() {
1163
- clearAdStallTimer();
1164
- if (!currentAdEventHandlers || !adVideoElement) return;
1165
- var el = adVideoElement;
1166
- el.removeEventListener("timeupdate", currentAdEventHandlers.timeupdate);
1167
- el.removeEventListener("playing", currentAdEventHandlers.playing);
1168
- el.removeEventListener("ended", currentAdEventHandlers.ended);
1169
- el.removeEventListener("error", currentAdEventHandlers.error);
1170
- el.removeEventListener("volumechange", currentAdEventHandlers.volumechange);
1171
- el.removeEventListener("pause", currentAdEventHandlers.pause);
1172
- el.removeEventListener("play", currentAdEventHandlers.play);
1173
- el.removeEventListener("waiting", currentAdEventHandlers.waiting);
1174
- currentAdEventHandlers = void 0;
1175
- }
1176
- function setupAdEventListeners() {
1177
- if (!adVideoElement) return;
1178
- removeAdEventListeners();
1179
- var handlers = {
1180
- timeupdate: function timeupdate() {
1181
- var ad = currentAd;
1182
- if (!ad || !adVideoElement) return;
1183
- var progress = adVideoElement.currentTime / ad.duration;
1184
- if (progress >= 0.25 && !trackingFired.firstQuartile) {
1185
- trackingFired.firstQuartile = true;
1186
- fireTrackingPixels2(ad.trackingUrls.firstQuartile);
1187
- }
1188
- if (progress >= 0.5 && !trackingFired.midpoint) {
1189
- trackingFired.midpoint = true;
1190
- fireTrackingPixels2(ad.trackingUrls.midpoint);
1191
- }
1192
- if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1193
- trackingFired.thirdQuartile = true;
1194
- fireTrackingPixels2(ad.trackingUrls.thirdQuartile);
1195
- }
1196
- },
1197
- playing: function playing() {
1198
- clearAdStallTimer();
1199
- var ad = currentAd;
1200
- if (!ad || trackingFired.start) return;
1201
- trackingFired.start = true;
1202
- fireTrackingPixels2(ad.trackingUrls.start);
1203
- if (debug) console.log("".concat(LOG, " Ad started playing"));
1204
- },
1205
- ended: function ended() {
1206
- if (tornDown || !currentAd || trackingFired.complete) return;
1207
- trackingFired.complete = true;
1208
- fireTrackingPixels2(currentAd.trackingUrls.complete);
1209
- if (debug) console.log("".concat(LOG, " Ad completed"));
1210
- handleAdComplete();
1211
- },
1212
- error: function error(e) {
1213
- if (tornDown) return;
1214
- console.error("".concat(LOG, " Ad video error:"), e);
1215
- if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);
1216
- handleAdError();
1217
- },
1218
- volumechange: function volumechange() {
1219
- if (!currentAd || !adVideoElement) return;
1220
- if (adVideoElement.muted) {
1221
- fireTrackingPixels2(currentAd.trackingUrls.mute);
1222
- } else {
1223
- fireTrackingPixels2(currentAd.trackingUrls.unmute);
1224
- }
1225
- },
1226
- pause: function pause() {
1227
- if (currentAd && adVideoElement && !adVideoElement.ended) {
1228
- fireTrackingPixels2(currentAd.trackingUrls.pause);
1229
- }
1230
- },
1231
- play: function play() {
1232
- if (currentAd && adVideoElement && adVideoElement.currentTime > 0) {
1233
- fireTrackingPixels2(currentAd.trackingUrls.resume);
1234
- }
1235
- },
1236
- waiting: function waiting() {
1237
- clearAdStallTimer();
1238
- adStallTimerId = setTimeout(function() {
1239
- adStallTimerId = void 0;
1240
- if (adPlaying) {
1241
- if (debug) console.warn("".concat(LOG, " Ad video stalled for too long, treating as error"));
1242
- handleAdError();
1243
- }
1244
- }, 8e3);
1245
- }
1246
- };
1247
- adVideoElement.addEventListener("timeupdate", handlers.timeupdate);
1248
- adVideoElement.addEventListener("playing", handlers.playing);
1249
- adVideoElement.addEventListener("ended", handlers.ended);
1250
- adVideoElement.addEventListener("error", handlers.error);
1251
- adVideoElement.addEventListener("volumechange", handlers.volumechange);
1252
- adVideoElement.addEventListener("pause", handlers.pause);
1253
- adVideoElement.addEventListener("play", handlers.play);
1254
- adVideoElement.addEventListener("waiting", handlers.waiting);
1255
- currentAdEventHandlers = handlers;
1256
- }
1257
- function setAdPlayingFlag(isPlaying) {
1258
- if (isPlaying) {
1259
- contentVideo.dataset.stormcloudAdPlaying = "true";
1260
- } else {
1261
- delete contentVideo.dataset.stormcloudAdPlaying;
1262
- }
1263
- }
1264
- function handleAdComplete() {
1265
- if (tornDown) return;
1266
- clearAdStallTimer();
1267
- if (debug) console.log("".concat(LOG, " Handling ad completion"));
1268
- adPlaying = false;
1269
- setAdPlayingFlag(false);
1270
- if (adContainerEl) {
1271
- adContainerEl.style.display = "none";
1272
- adContainerEl.style.pointerEvents = "none";
1273
- }
1274
- emit("ad_impression");
1275
- emit("content_resume");
1276
- }
1277
- function handleAdError() {
1278
- if (tornDown) return;
1279
- if (!adPlaying) return;
1280
- clearAdStallTimer();
1281
- if (debug) console.log("".concat(LOG, " Handling ad error"));
1282
- adPlaying = false;
1283
- setAdPlayingFlag(false);
1284
- if (adContainerEl) {
1285
- adContainerEl.style.display = "none";
1286
- adContainerEl.style.pointerEvents = "none";
1287
- }
1288
- emit("ad_error");
1289
- }
1290
- function teardownCurrentPlayback() {
1291
- removeAdEventListeners();
1292
- if (adHls) {
1293
- adHls.destroy();
1294
- adHls = void 0;
1209
+ function getDurationSecondsFromContext(requestContext) {
1210
+ var _ctx_remainingBreakSec;
1211
+ if (!requestContext || (typeof requestContext === "undefined" ? "undefined" : _type_of(requestContext)) !== "object") {
1212
+ return 30;
1295
1213
  }
1296
- if (adVideoElement) {
1297
- if (singleElementMode && adVideoElement === contentVideo) {
1298
- contentVideo.pause();
1299
- } else {
1300
- adVideoElement.pause();
1301
- adVideoElement.removeAttribute("src");
1302
- adVideoElement.load();
1303
- }
1214
+ var ctx = requestContext;
1215
+ var value = (_ctx_remainingBreakSec = ctx.remainingBreakSec) !== null && _ctx_remainingBreakSec !== void 0 ? _ctx_remainingBreakSec : ctx.breakDurationSec;
1216
+ if (typeof value !== "number" || Number.isNaN(value)) {
1217
+ return 30;
1304
1218
  }
1219
+ return Math.max(1, Math.ceil(value));
1305
1220
  }
1306
- function startNativePlayback(mediaFile) {
1307
- if (!adVideoElement) return;
1308
- if (debug) console.log("".concat(LOG, " Starting native MP4 playback: ").concat(mediaFile.url));
1309
- adVideoElement.src = mediaFile.url;
1310
- adVideoElement.load();
1311
- adVideoElement.play().catch(function(error) {
1312
- console.error("".concat(LOG, " Error starting native ad playback:"), error);
1313
- handleAdError();
1314
- });
1315
- }
1316
- function startHlsPlayback(mediaFile) {
1317
- if (!adVideoElement) return;
1318
- if (debug) console.log("".concat(LOG, " Starting HLS playback: ").concat(mediaFile.url));
1319
- if (import_hls.default.isSupported()) {
1320
- if (adHls) {
1321
- adHls.destroy();
1322
- adHls = void 0;
1323
- }
1324
- adHls = new import_hls.default({
1325
- enableWorker: true,
1326
- lowLatencyMode: false
1327
- });
1328
- adHls.loadSource(mediaFile.url);
1329
- adHls.attachMedia(adVideoElement);
1330
- adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
1331
- if (!adPlaying) return;
1332
- adVideoElement.play().catch(function(error) {
1333
- console.error("".concat(LOG, " Error starting HLS ad playback:"), error);
1334
- handleAdError();
1335
- });
1336
- });
1337
- var nonFatalNetworkErrors = 0;
1338
- adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
1339
- if (data.fatal) {
1340
- handleAdError();
1341
- } else if (data.type === import_hls.default.ErrorTypes.NETWORK_ERROR) {
1342
- nonFatalNetworkErrors++;
1343
- if (nonFatalNetworkErrors >= 3) {
1344
- if (debug) console.warn("".concat(LOG, " Too many non-fatal HLS network errors (").concat(nonFatalNetworkErrors, "), treating as fatal"));
1345
- handleAdError();
1346
- }
1347
- }
1348
- });
1349
- } else if (adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
1350
- adVideoElement.src = mediaFile.url;
1351
- adVideoElement.play().catch(function(error) {
1352
- console.error("".concat(LOG, " Error starting native HLS ad playback:"), error);
1353
- handleAdError();
1354
- });
1355
- } else {
1356
- console.error("".concat(LOG, " HLS not supported on this platform"));
1357
- handleAdError();
1358
- }
1359
- }
1360
- function startPlayback(mediaFile) {
1361
- if (!adVideoElement) return;
1362
- if (singleElementMode && isHlsMediaFile(mediaFile)) {
1363
- var mp4Fallback = currentAd === null || currentAd === void 0 ? void 0 : currentAd.mediaFiles.find(function(f) {
1364
- return !isHlsMediaFile(f);
1365
- });
1366
- if (mp4Fallback) {
1367
- if (debug) console.log("".concat(LOG, " singleElementMode: HLS ad blocked, using MP4 fallback"));
1368
- startNativePlayback(mp4Fallback);
1369
- return;
1370
- }
1371
- }
1372
- if (isHlsMediaFile(mediaFile)) {
1373
- startHlsPlayback(mediaFile);
1374
- } else {
1375
- startNativePlayback(mediaFile);
1376
- }
1377
- }
1378
- function playAd(bids) {
1221
+ function requestAdFromApi(requestContext) {
1379
1222
  return _async_to_generator(function() {
1380
- var winner, ad, contentVolume, adVolume2, mediaFile2, _contentVideo_parentElement, container, adVolume, mediaFile;
1223
+ var durationSeconds, ads;
1381
1224
  return _ts_generator(this, function(_state) {
1382
1225
  switch(_state.label){
1383
1226
  case 0:
1384
- if (destroyed) {
1385
- return [
1386
- 2,
1387
- Promise.reject(new Error("Layer has been destroyed"))
1388
- ];
1389
- }
1390
- if (bids.length === 0) {
1391
- return [
1392
- 2,
1393
- Promise.reject(new Error("No bids provided"))
1394
- ];
1395
- }
1396
- winner = bids[0];
1397
- if (debug) {
1398
- console.log("".concat(LOG, " Winning bid: ").concat(winner.bidder, " $").concat(winner.cpm.toFixed(2), " ").concat(winner.currency));
1399
- }
1227
+ durationSeconds = getDurationSecondsFromContext(requestContext);
1400
1228
  return [
1401
1229
  4,
1402
- resolveBidToVastAd(winner, LOG)
1230
+ fetchVast(durationSeconds)
1403
1231
  ];
1404
1232
  case 1:
1405
- ad = _state.sent();
1406
- if (!ad) {
1407
- if (debug) console.warn("".concat(LOG, " Winning bid has no VAST URL or XML"));
1408
- emit("ad_error");
1409
- return [
1410
- 2,
1411
- Promise.reject(new Error("No VAST from bid"))
1412
- ];
1413
- }
1414
- if (debug) {
1415
- console.log("".concat(LOG, " Ad parsed: ").concat(ad.title, ", duration: ").concat(ad.duration, "s, mediaFiles: ").concat(ad.mediaFiles.length));
1416
- }
1417
- sessionId = generateSessionId();
1418
- currentAd = ad;
1419
- trackingFired = _object_spread({}, createEmptyTrackingState());
1420
- fireTrackingPixels2(ad.trackingUrls.impression);
1421
- trackingFired.impression = true;
1422
- contentVolume = contentVideo.volume;
1423
- originalVolume = Math.max(0, Math.min(1, contentVolume || originalVolume));
1424
- if (!singleElementMode) return [
1425
- 3,
1426
- 3
1427
- ];
1428
- mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.detachMedia();
1429
- teardownCurrentPlayback();
1430
- adVideoElement = contentVideo;
1431
- adHls = void 0;
1432
- adPlaying = true;
1433
- setAdPlayingFlag(true);
1434
- contentVideo.removeAttribute("src");
1435
- contentVideo.load();
1436
- if (!continueLiveStreamDuringAds) {
1437
- contentVideo.pause();
1438
- }
1439
- contentVideo.muted = true;
1440
- contentVideo.volume = 0;
1441
- return [
1442
- 4,
1443
- new Promise(function(resolve) {
1444
- return setTimeout(resolve, 200);
1445
- })
1446
- ];
1447
- case 2:
1448
- _state.sent();
1449
- if (destroyed || tornDown) return [
1450
- 2
1451
- ];
1452
- contentVideo.style.visibility = "visible";
1453
- contentVideo.style.opacity = "1";
1454
- emit("content_pause");
1455
- setupAdEventListeners();
1456
- adVolume2 = originalMutedState ? 1 : originalVolume;
1457
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume2));
1458
- adVideoElement.muted = false;
1459
- mediaFile2 = selectBestMediaFile(ad.mediaFiles);
1460
- if (debug) console.log("".concat(LOG, " Loading ad from: ").concat(mediaFile2.url));
1461
- startPlayback(mediaFile2);
1462
- return [
1463
- 2
1464
- ];
1465
- case 3:
1466
- if (!adContainerEl) {
1467
- ;
1468
- container = document.createElement("div");
1469
- container.style.position = "absolute";
1470
- container.style.left = "0";
1471
- container.style.top = "0";
1472
- container.style.right = "0";
1473
- container.style.bottom = "0";
1474
- container.style.display = "none";
1475
- container.style.alignItems = "center";
1476
- container.style.justifyContent = "center";
1477
- container.style.pointerEvents = "none";
1478
- container.style.zIndex = "10";
1479
- container.style.backgroundColor = "#000";
1480
- (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1481
- adContainerEl = container;
1482
- }
1483
- if (!adVideoElement) {
1484
- adVideoElement = createAdVideoElement();
1485
- adContainerEl.appendChild(adVideoElement);
1486
- setupAdEventListeners();
1487
- } else {
1488
- teardownCurrentPlayback();
1489
- }
1490
- if (!continueLiveStreamDuringAds) {
1491
- contentVideo.pause();
1492
- }
1493
- contentVideo.muted = true;
1494
- contentVideo.volume = 0;
1495
- adPlaying = true;
1496
- setAdPlayingFlag(true);
1497
- adVolume = originalMutedState ? 1 : originalVolume;
1498
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume));
1499
- adVideoElement.muted = false;
1500
- if (adContainerEl) {
1501
- adContainerEl.style.display = "flex";
1502
- adContainerEl.style.pointerEvents = "auto";
1503
- }
1504
- emit("content_pause");
1505
- mediaFile = selectBestMediaFile(ad.mediaFiles);
1506
- if (debug) console.log("".concat(LOG, " Loading ad from: ").concat(mediaFile.url));
1507
- startPlayback(mediaFile);
1233
+ ads = _state.sent();
1508
1234
  return [
1509
- 2
1235
+ 2,
1236
+ ads[0] || null
1510
1237
  ];
1511
1238
  }
1512
1239
  });
1513
1240
  })();
1514
1241
  }
1515
- function ensureAdContainer() {
1516
- if (!adContainerEl) {
1517
- var _contentVideo_parentElement;
1518
- var container = document.createElement("div");
1519
- container.style.position = "absolute";
1520
- container.style.left = "0";
1521
- container.style.top = "0";
1522
- container.style.right = "0";
1523
- container.style.bottom = "0";
1524
- container.style.display = "none";
1525
- container.style.alignItems = "center";
1526
- container.style.justifyContent = "center";
1527
- container.style.pointerEvents = "none";
1528
- container.style.zIndex = "10";
1529
- container.style.backgroundColor = "#000";
1530
- (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1531
- adContainerEl = container;
1532
- }
1533
- return adContainerEl;
1242
+ function assignCurrentAd(ad) {
1243
+ currentAd = ad;
1244
+ sessionId = generateSessionId();
1245
+ trackingFired = {
1246
+ impression: false,
1247
+ start: false,
1248
+ firstQuartile: false,
1249
+ midpoint: false,
1250
+ thirdQuartile: false,
1251
+ complete: false
1252
+ };
1253
+ fireTrackingPixels2(currentAd.trackingUrls.impression);
1254
+ trackingFired.impression = true;
1255
+ emit("ad_impression");
1534
1256
  }
1535
- function preloadAd(bids, token) {
1536
- return _async_to_generator(function() {
1537
- var winner, ad, mediaFile, slot, videoEl, container, hls, slot1, slot2;
1538
- return _ts_generator(this, function(_state) {
1539
- switch(_state.label){
1540
- case 0:
1541
- if (destroyed) return [
1542
- 2
1543
- ];
1544
- winner = bids[0];
1545
- if (!winner) return [
1546
- 2
1547
- ];
1548
- if (debug) console.log("".concat(LOG, " [preload] Resolving VAST for token=").concat(token));
1549
- return [
1550
- 4,
1551
- resolveBidToVastAd(winner, LOG)
1552
- ];
1553
- case 1:
1554
- ad = _state.sent();
1555
- if (!ad || destroyed) return [
1556
- 2
1557
- ];
1558
- mediaFile = selectBestMediaFile(ad.mediaFiles);
1559
- if (!mediaFile) return [
1560
- 2
1561
- ];
1562
- if (smartTVMode || singleElementMode) {
1563
- slot = {
1564
- bids: bids,
1565
- ad: ad,
1566
- mediaFile: mediaFile,
1567
- videoEl: null,
1568
- ready: true
1569
- };
1570
- preloadSlots.set(token, slot);
1571
- if (debug) console.log("".concat(LOG, " [preload] Metadata-only preload (smartTV/singleElement), token=").concat(token, ", url=").concat(mediaFile.url));
1572
- return [
1573
- 2
1574
- ];
1575
- }
1576
- videoEl = createAdVideoElement();
1577
- videoEl.style.visibility = "hidden";
1578
- videoEl.style.pointerEvents = "none";
1579
- videoEl.preload = "auto";
1580
- container = ensureAdContainer();
1581
- container.appendChild(videoEl);
1582
- if (isHlsMediaFile(mediaFile) && import_hls.default.isSupported()) {
1583
- hls = new import_hls.default({
1584
- enableWorker: true,
1585
- lowLatencyMode: false
1586
- });
1587
- hls.loadSource(mediaFile.url);
1588
- hls.attachMedia(videoEl);
1589
- slot1 = {
1590
- bids: bids,
1591
- ad: ad,
1592
- mediaFile: mediaFile,
1593
- videoEl: videoEl,
1594
- hlsInstance: hls,
1595
- ready: false
1596
- };
1597
- preloadSlots.set(token, slot1);
1598
- hls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
1599
- var s = preloadSlots.get(token);
1600
- if (s) s.ready = true;
1601
- if (debug) console.log("".concat(LOG, " [preload] HLS manifest parsed, token=").concat(token));
1602
- });
1603
- hls.on(import_hls.default.Events.ERROR, function(_evt, data) {
1604
- if (!preloadSlots.has(token)) return;
1605
- if (data.fatal) {
1606
- if (debug) console.warn("".concat(LOG, " [preload] HLS error for token=").concat(token));
1607
- preloadSlots.delete(token);
1608
- hls.destroy();
1609
- videoEl.remove();
1610
- }
1611
- });
1612
- } else {
1613
- videoEl.src = mediaFile.url;
1614
- videoEl.load();
1615
- slot2 = {
1616
- bids: bids,
1617
- ad: ad,
1618
- mediaFile: mediaFile,
1619
- videoEl: videoEl,
1620
- ready: false
1621
- };
1622
- preloadSlots.set(token, slot2);
1623
- videoEl.addEventListener("canplay", function() {
1624
- var s = preloadSlots.get(token);
1625
- if (s) s.ready = true;
1626
- if (debug) console.log("".concat(LOG, " [preload] canplay fired, token=").concat(token));
1627
- }, {
1628
- once: true
1629
- });
1630
- }
1631
- if (debug) console.log("".concat(LOG, " [preload] Started buffering token=").concat(token, ", url=").concat(mediaFile.url));
1632
- return [
1633
- 2
1634
- ];
1257
+ return {
1258
+ initialize: function initialize() {
1259
+ log("Initializing");
1260
+ if (!adContainerEl) {
1261
+ var _contentVideo_parentElement;
1262
+ var parent = contentVideo.parentElement;
1263
+ if (parent) {
1264
+ var computed = window.getComputedStyle(parent).position;
1265
+ if (computed === "static") {
1266
+ parent.style.position = "relative";
1267
+ parentPositionOverridden = true;
1268
+ }
1635
1269
  }
1636
- });
1637
- })();
1638
- }
1639
- function playPreloaded(token) {
1640
- return _async_to_generator(function() {
1641
- var slot, contentVolume, adVolume2, videoEl, container2, adVolume21, nonFatalNetworkErrors, adVolume, container;
1642
- return _ts_generator(this, function(_state) {
1643
- switch(_state.label){
1644
- case 0:
1645
- if (destroyed) return [
1646
- 2,
1647
- Promise.reject(new Error("Layer has been destroyed"))
1648
- ];
1649
- slot = preloadSlots.get(token);
1650
- if (!slot) {
1651
- if (debug) console.warn("".concat(LOG, " [preload] No slot found for token=").concat(token, ", nothing to play"));
1270
+ var container = document.createElement("div");
1271
+ container.style.position = "absolute";
1272
+ container.style.left = "0";
1273
+ container.style.top = "0";
1274
+ container.style.right = "0";
1275
+ container.style.bottom = "0";
1276
+ container.style.display = "none";
1277
+ container.style.alignItems = "center";
1278
+ container.style.justifyContent = "center";
1279
+ container.style.pointerEvents = "none";
1280
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1281
+ container.style.backgroundColor = "#000";
1282
+ container.style.transition = "opacity 0.3s ease-in-out";
1283
+ container.style.opacity = "0";
1284
+ container.style.isolation = "isolate";
1285
+ var countdown = document.createElement("div");
1286
+ countdown.style.position = "absolute";
1287
+ countdown.style.left = "12px";
1288
+ countdown.style.top = "12px";
1289
+ countdown.style.padding = "4px 8px";
1290
+ countdown.style.borderRadius = "4px";
1291
+ countdown.style.background = "rgba(0,0,0,0.75)";
1292
+ countdown.style.color = "#fff";
1293
+ countdown.style.fontFamily = "sans-serif";
1294
+ countdown.style.fontSize = "12px";
1295
+ countdown.style.lineHeight = "1.2";
1296
+ countdown.style.pointerEvents = "none";
1297
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1298
+ countdown.textContent = "Ad";
1299
+ container.appendChild(countdown);
1300
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1301
+ adContainerEl = container;
1302
+ adCountdownEl = countdown;
1303
+ }
1304
+ },
1305
+ requestAds: function requestAds(duration) {
1306
+ return _async_to_generator(function() {
1307
+ var durationSeconds, parsed, ads, error;
1308
+ return _ts_generator(this, function(_state) {
1309
+ switch(_state.label){
1310
+ case 0:
1311
+ log("Requesting ads for duration:", duration);
1312
+ if (adPlaying) {
1313
+ return [
1314
+ 2,
1315
+ Promise.reject(new Error("Ad already playing"))
1316
+ ];
1317
+ }
1318
+ if (destroyed) {
1319
+ return [
1320
+ 2,
1321
+ Promise.reject(new Error("Player has been destroyed"))
1322
+ ];
1323
+ }
1324
+ _state.label = 1;
1325
+ case 1:
1326
+ _state.trys.push([
1327
+ 1,
1328
+ 3,
1329
+ ,
1330
+ 4
1331
+ ]);
1332
+ tornDown = false;
1333
+ durationSeconds = 30;
1334
+ parsed = parseInt(duration || "", 10);
1335
+ if (!isNaN(parsed) && parsed > 0) {
1336
+ durationSeconds = parsed;
1337
+ }
1652
1338
  return [
1653
- 2
1339
+ 4,
1340
+ fetchVast(durationSeconds)
1654
1341
  ];
1655
- }
1656
- preloadSlots.delete(token);
1657
- if (debug) console.log("".concat(LOG, " [preload] Playing preloaded ad, token=").concat(token, ", ready=").concat(slot.ready));
1658
- contentVolume = contentVideo.volume;
1659
- originalVolume = Math.max(0, Math.min(1, contentVolume || originalVolume));
1660
- sessionId = generateSessionId();
1661
- currentAd = slot.ad;
1662
- trackingFired = _object_spread({}, createEmptyTrackingState());
1663
- fireTrackingPixels2(slot.ad.trackingUrls.impression);
1664
- trackingFired.impression = true;
1665
- if (!singleElementMode) return [
1666
- 3,
1667
- 2
1668
- ];
1669
- mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.detachMedia();
1670
- teardownCurrentPlayback();
1671
- adVideoElement = contentVideo;
1672
- adHls = void 0;
1673
- adPlaying = true;
1674
- setAdPlayingFlag(true);
1675
- contentVideo.removeAttribute("src");
1676
- contentVideo.load();
1677
- contentVideo.muted = true;
1678
- contentVideo.volume = 0;
1679
- return [
1680
- 4,
1681
- new Promise(function(resolve) {
1682
- return setTimeout(resolve, 200);
1683
- })
1684
- ];
1685
- case 1:
1686
- _state.sent();
1687
- if (destroyed || tornDown) return [
1688
- 2
1689
- ];
1690
- contentVideo.style.visibility = "visible";
1691
- contentVideo.style.opacity = "1";
1692
- emit("content_pause");
1693
- setupAdEventListeners();
1694
- adVolume2 = originalMutedState ? 1 : originalVolume;
1695
- contentVideo.volume = Math.max(0, Math.min(1, adVolume2));
1696
- contentVideo.muted = false;
1697
- if (debug) console.log("".concat(LOG, " [preload] singleElementMode: attaching ad to contentVideo, url=").concat(slot.mediaFile.url));
1698
- startPlayback(slot.mediaFile);
1699
- return [
1700
- 2
1701
- ];
1702
- case 2:
1703
- if (smartTVMode && !slot.videoEl) {
1704
- teardownCurrentPlayback();
1705
- if (adVideoElement) {
1706
- adVideoElement.remove();
1707
- adVideoElement = void 0;
1342
+ case 2:
1343
+ ads = _state.sent();
1344
+ if (ads.length === 0) {
1345
+ log("No ads available from VAST response");
1346
+ emit("ad_error");
1347
+ return [
1348
+ 2,
1349
+ Promise.resolve()
1350
+ ];
1351
+ }
1352
+ assignCurrentAd(ads[0]);
1353
+ log("Ad loaded: ".concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
1354
+ return [
1355
+ 2,
1356
+ Promise.resolve()
1357
+ ];
1358
+ case 3:
1359
+ error = _state.sent();
1360
+ console.error("[AdStormPlayer] Error requesting ads:", error);
1361
+ emit("ad_error");
1362
+ return [
1363
+ 2,
1364
+ Promise.reject(error)
1365
+ ];
1366
+ case 4:
1367
+ return [
1368
+ 2
1369
+ ];
1370
+ }
1371
+ });
1372
+ })();
1373
+ },
1374
+ play: function play() {
1375
+ return _async_to_generator(function() {
1376
+ var mediaFile, error;
1377
+ return _ts_generator(this, function(_state) {
1378
+ switch(_state.label){
1379
+ case 0:
1380
+ if (!currentAd) {
1381
+ return [
1382
+ 2,
1383
+ Promise.reject(new Error("No ad loaded"))
1384
+ ];
1385
+ }
1386
+ if (destroyed) {
1387
+ return [
1388
+ 2,
1389
+ Promise.reject(new Error("Player has been destroyed"))
1390
+ ];
1391
+ }
1392
+ log("Starting ad playback");
1393
+ _state.label = 1;
1394
+ case 1:
1395
+ _state.trys.push([
1396
+ 1,
1397
+ 3,
1398
+ ,
1399
+ 4
1400
+ ]);
1401
+ tornDown = false;
1402
+ if (adHideTimerId) {
1403
+ clearTimeout(adHideTimerId);
1404
+ adHideTimerId = void 0;
1405
+ }
1406
+ if (!adVideoElement) {
1407
+ adVideoElement = createAdVideoElement();
1408
+ adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.appendChild(adVideoElement);
1409
+ } else {
1410
+ teardownCurrentPlayback();
1708
1411
  }
1709
- videoEl = createAdVideoElement();
1710
- videoEl.style.visibility = "visible";
1711
- videoEl.style.pointerEvents = "none";
1712
- container2 = ensureAdContainer();
1713
- container2.appendChild(videoEl);
1714
- adVideoElement = videoEl;
1715
1412
  setupAdEventListeners();
1413
+ trackingFired = {
1414
+ impression: trackingFired.impression,
1415
+ start: false,
1416
+ firstQuartile: false,
1417
+ midpoint: false,
1418
+ thirdQuartile: false,
1419
+ complete: false
1420
+ };
1421
+ contentVideo.style.transition = "opacity 0.3s ease-in-out";
1422
+ contentVideo.style.opacity = "0";
1423
+ setTimeout(function() {
1424
+ contentVideo.style.visibility = "hidden";
1425
+ }, 300);
1426
+ contentVideo.muted = true;
1427
+ contentVideo.volume = 0;
1716
1428
  if (!continueLiveStreamDuringAds) {
1717
1429
  contentVideo.pause();
1718
1430
  }
1719
- contentVideo.muted = true;
1720
- contentVideo.volume = 0;
1721
1431
  adPlaying = true;
1722
1432
  setAdPlayingFlag(true);
1723
- adVolume21 = originalMutedState ? 1 : originalVolume;
1724
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume21));
1725
- adVideoElement.muted = false;
1726
- container2.style.display = "flex";
1727
- container2.style.pointerEvents = "auto";
1433
+ if (adVideoElement) {
1434
+ adVideoElement.volume = originalMutedState ? 0 : originalVolume;
1435
+ adVideoElement.muted = originalMutedState;
1436
+ }
1437
+ if (adContainerEl) {
1438
+ adContainerEl.style.display = "flex";
1439
+ adContainerEl.style.pointerEvents = "auto";
1440
+ adContainerEl.offsetHeight;
1441
+ adContainerEl.style.opacity = "1";
1442
+ }
1728
1443
  emit("content_pause");
1729
- if (debug) console.log("".concat(LOG, " [preload] smartTVMode deferred: creating video element and loading, url=").concat(slot.mediaFile.url));
1730
- startPlayback(slot.mediaFile);
1444
+ mediaFile = selectBestMediaFile(currentAd.mediaFiles);
1445
+ if (!mediaFile) {
1446
+ throw new Error("No media file available");
1447
+ }
1448
+ log("Playing media file:", mediaFile.url);
1449
+ adVideoElement.src = mediaFile.url;
1450
+ adVideoElement.load();
1731
1451
  return [
1732
- 2
1452
+ 4,
1453
+ adVideoElement.play()
1733
1454
  ];
1734
- }
1735
- teardownCurrentPlayback();
1736
- if (adVideoElement && adVideoElement !== slot.videoEl) {
1737
- adVideoElement.remove();
1738
- }
1739
- slot.videoEl.style.visibility = "visible";
1740
- slot.videoEl.style.pointerEvents = "none";
1741
- adVideoElement = slot.videoEl;
1742
- adHls = slot.hlsInstance;
1743
- if (adHls) {
1744
- nonFatalNetworkErrors = 0;
1745
- adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
1746
- if (!adPlaying) return;
1747
- if (data.fatal) {
1748
- handleAdError();
1749
- } else if (data.type === import_hls.default.ErrorTypes.NETWORK_ERROR) {
1750
- nonFatalNetworkErrors++;
1751
- if (nonFatalNetworkErrors >= 3) {
1752
- if (debug) console.warn("".concat(LOG, " [preload] Too many non-fatal HLS network errors during playback, treating as fatal"));
1753
- handleAdError();
1754
- }
1755
- }
1756
- });
1757
- }
1758
- setupAdEventListeners();
1759
- if (!continueLiveStreamDuringAds) {
1760
- contentVideo.pause();
1761
- }
1762
- contentVideo.muted = true;
1763
- contentVideo.volume = 0;
1764
- adPlaying = true;
1765
- setAdPlayingFlag(true);
1766
- adVolume = originalMutedState ? 1 : originalVolume;
1767
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume));
1768
- adVideoElement.muted = false;
1769
- container = ensureAdContainer();
1770
- container.style.display = "flex";
1771
- container.style.pointerEvents = "auto";
1772
- emit("content_pause");
1773
- adVideoElement.play().catch(function(error) {
1774
- console.error("".concat(LOG, " [preload] Error playing preloaded ad:"), error);
1455
+ case 2:
1456
+ _state.sent();
1457
+ return [
1458
+ 2,
1459
+ Promise.resolve()
1460
+ ];
1461
+ case 3:
1462
+ error = _state.sent();
1463
+ console.error("[AdStormPlayer] Error playing ad:", error);
1775
1464
  handleAdError();
1776
- });
1777
- return [
1778
- 2
1779
- ];
1780
- }
1781
- });
1782
- })();
1783
- }
1784
- function cancelPreload(token) {
1785
- var slot = preloadSlots.get(token);
1786
- if (!slot) return;
1787
- preloadSlots.delete(token);
1788
- if (slot.hlsInstance) {
1789
- slot.hlsInstance.destroy();
1790
- }
1791
- if (slot.videoEl) {
1792
- slot.videoEl.pause();
1793
- slot.videoEl.removeAttribute("src");
1794
- slot.videoEl.load();
1795
- slot.videoEl.remove();
1796
- }
1797
- if (debug) console.log("".concat(LOG, " [preload] Cancelled and cleaned up token=").concat(token));
1798
- }
1799
- return {
1800
- initialize: function initialize() {
1801
- if (debug) console.log("".concat(LOG, " Initializing"));
1802
- },
1803
- updateOptions: function updateOptions(opts) {
1804
- if (opts.continueLiveStreamDuringAds !== void 0) {
1805
- continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;
1806
- }
1807
- if (opts.mainHlsInstance !== void 0) {
1808
- var _opts_mainHlsInstance;
1809
- mainHlsInstance = (_opts_mainHlsInstance = opts.mainHlsInstance) !== null && _opts_mainHlsInstance !== void 0 ? _opts_mainHlsInstance : void 0;
1810
- }
1811
- },
1812
- playAd: playAd,
1813
- preloadAd: preloadAd,
1814
- playPreloaded: playPreloaded,
1815
- hasPreloaded: function hasPreloaded(token) {
1816
- return preloadSlots.has(token);
1817
- },
1818
- cancelPreload: cancelPreload,
1819
- pause: function pause() {
1820
- if (!adPlaying || !adVideoElement) return;
1821
- try {
1822
- if (!adVideoElement.paused) adVideoElement.pause();
1823
- } catch (error) {
1824
- if (debug) console.warn("".concat(LOG, " Error pausing ad:"), error);
1825
- }
1826
- },
1827
- resume: function resume() {
1828
- if (!adPlaying || !adVideoElement) return;
1829
- try {
1830
- if (adVideoElement.paused) adVideoElement.play().catch(function() {});
1831
- } catch (error) {
1832
- if (debug) console.warn("".concat(LOG, " Error resuming ad:"), error);
1833
- }
1465
+ return [
1466
+ 2,
1467
+ Promise.reject(error)
1468
+ ];
1469
+ case 4:
1470
+ return [
1471
+ 2
1472
+ ];
1473
+ }
1474
+ });
1475
+ })();
1834
1476
  },
1835
1477
  stop: function stop() {
1836
1478
  return _async_to_generator(function() {
1837
1479
  return _ts_generator(this, function(_state) {
1480
+ log("Stopping ad");
1838
1481
  tornDown = true;
1839
- if (debug) console.log("".concat(LOG, " Stopping ad"));
1840
1482
  adPlaying = false;
1841
1483
  setAdPlayingFlag(false);
1842
- contentVideo.muted = originalMutedState;
1843
- contentVideo.volume = originalMutedState ? 0 : originalVolume;
1484
+ clearAdStallTimer();
1485
+ clearAdCountdownTimer();
1486
+ if (adContainerEl) {
1487
+ adContainerEl.style.opacity = "0";
1488
+ adHideTimerId = setTimeout(function() {
1489
+ if (adContainerEl) {
1490
+ adContainerEl.style.display = "none";
1491
+ adContainerEl.style.pointerEvents = "none";
1492
+ }
1493
+ }, 300);
1494
+ }
1495
+ teardownCurrentPlayback();
1844
1496
  contentVideo.style.visibility = "visible";
1845
1497
  contentVideo.style.opacity = "1";
1846
- if (singleElementMode) {
1847
- teardownCurrentPlayback();
1848
- contentVideo.removeAttribute("src");
1849
- contentVideo.load();
1850
- adVideoElement = void 0;
1851
- } else {
1852
- if (adContainerEl) {
1853
- adContainerEl.style.display = "none";
1854
- adContainerEl.style.pointerEvents = "none";
1855
- }
1856
- if (continueLiveStreamDuringAds) {
1857
- contentVideo.play().catch(function() {});
1858
- }
1859
- teardownCurrentPlayback();
1860
- if (adVideoElement) {
1861
- adVideoElement.pause();
1862
- adVideoElement.removeAttribute("src");
1863
- adVideoElement.load();
1864
- }
1865
- }
1498
+ contentVideo.muted = originalMutedState;
1499
+ contentVideo.volume = originalVolume;
1866
1500
  currentAd = void 0;
1867
1501
  tornDown = false;
1868
1502
  return [
1869
- 2
1503
+ 2,
1504
+ Promise.resolve()
1870
1505
  ];
1871
1506
  });
1872
1507
  })();
1873
1508
  },
1509
+ pause: function pause() {
1510
+ if (!adPlaying || !adVideoElement) return;
1511
+ try {
1512
+ if (!adVideoElement.paused) adVideoElement.pause();
1513
+ } catch (error) {
1514
+ console.warn("[AdStormPlayer] Error pausing ad:", error);
1515
+ }
1516
+ },
1517
+ resume: function resume() {
1518
+ if (!adPlaying || !adVideoElement) return;
1519
+ try {
1520
+ if (adVideoElement.paused) adVideoElement.play().catch(function() {});
1521
+ } catch (error) {
1522
+ console.warn("[AdStormPlayer] Error resuming ad:", error);
1523
+ }
1524
+ },
1874
1525
  destroy: function destroy() {
1875
- tornDown = true;
1876
- if (debug) console.log("".concat(LOG, " Destroying"));
1526
+ log("Destroying");
1877
1527
  destroyed = true;
1528
+ tornDown = true;
1878
1529
  adPlaying = false;
1879
1530
  setAdPlayingFlag(false);
1531
+ clearAdStallTimer();
1532
+ clearAdCountdownTimer();
1533
+ if (adHideTimerId) {
1534
+ clearTimeout(adHideTimerId);
1535
+ adHideTimerId = void 0;
1536
+ }
1880
1537
  contentVideo.muted = originalMutedState;
1881
1538
  contentVideo.volume = originalVolume;
1882
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1883
- try {
1884
- for(var _iterator = Array.from(preloadSlots.entries())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1885
- var _step_value = _sliced_to_array(_step.value, 1), token = _step_value[0];
1886
- cancelPreload(token);
1887
- }
1888
- } catch (err) {
1889
- _didIteratorError = true;
1890
- _iteratorError = err;
1891
- } finally{
1892
- try {
1893
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1894
- _iterator.return();
1895
- }
1896
- } finally{
1897
- if (_didIteratorError) {
1898
- throw _iteratorError;
1899
- }
1900
- }
1901
- }
1539
+ contentVideo.style.visibility = "visible";
1540
+ contentVideo.style.opacity = "1";
1902
1541
  teardownCurrentPlayback();
1903
- if (adVideoElement) {
1904
- if (singleElementMode && adVideoElement === contentVideo) {
1905
- contentVideo.removeAttribute("src");
1906
- contentVideo.load();
1907
- } else {
1908
- adVideoElement.pause();
1909
- adVideoElement.removeAttribute("src");
1910
- adVideoElement.remove();
1911
- }
1912
- adVideoElement = void 0;
1913
- }
1542
+ adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.remove();
1543
+ adVideoElement = void 0;
1914
1544
  if (adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.parentElement) {
1915
1545
  adContainerEl.parentElement.removeChild(adContainerEl);
1916
1546
  }
1917
1547
  adContainerEl = void 0;
1548
+ adCountdownEl = void 0;
1918
1549
  currentAd = void 0;
1550
+ sessionId = void 0;
1551
+ preloadSlots.clear();
1919
1552
  listeners.clear();
1553
+ if (parentPositionOverridden && contentVideo.parentElement) {
1554
+ contentVideo.parentElement.style.position = "";
1555
+ parentPositionOverridden = false;
1556
+ }
1557
+ },
1558
+ updateOptions: function updateOptions(opts) {
1559
+ if (opts.continueLiveStreamDuringAds !== void 0) {
1560
+ continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;
1561
+ }
1562
+ },
1563
+ playAd: function playAd(requestContext) {
1564
+ return _async_to_generator(function() {
1565
+ var ad;
1566
+ return _ts_generator(this, function(_state) {
1567
+ switch(_state.label){
1568
+ case 0:
1569
+ if (destroyed) return [
1570
+ 2,
1571
+ Promise.reject(new Error("Player has been destroyed"))
1572
+ ];
1573
+ if (!!currentAd) return [
1574
+ 3,
1575
+ 2
1576
+ ];
1577
+ return [
1578
+ 4,
1579
+ requestAdFromApi(requestContext)
1580
+ ];
1581
+ case 1:
1582
+ ad = _state.sent();
1583
+ if (!ad) {
1584
+ emit("ad_error", {
1585
+ message: "No valid ad from AdStorm API"
1586
+ });
1587
+ return [
1588
+ 2,
1589
+ Promise.reject(new Error("No valid ad from AdStorm API"))
1590
+ ];
1591
+ }
1592
+ assignCurrentAd(ad);
1593
+ _state.label = 2;
1594
+ case 2:
1595
+ return [
1596
+ 2,
1597
+ this.play()
1598
+ ];
1599
+ }
1600
+ });
1601
+ }).call(this);
1602
+ },
1603
+ preloadAd: function preloadAd(arg1, arg2) {
1604
+ return _async_to_generator(function() {
1605
+ var token, requestContext, ad;
1606
+ return _ts_generator(this, function(_state) {
1607
+ switch(_state.label){
1608
+ case 0:
1609
+ if (destroyed) return [
1610
+ 2
1611
+ ];
1612
+ token = typeof arg1 === "string" ? arg1 : typeof arg2 === "string" ? arg2 : void 0;
1613
+ if (!token) return [
1614
+ 2
1615
+ ];
1616
+ requestContext = typeof arg1 === "string" ? arg2 : arg1;
1617
+ return [
1618
+ 4,
1619
+ requestAdFromApi(requestContext)
1620
+ ];
1621
+ case 1:
1622
+ ad = _state.sent();
1623
+ if (!ad) return [
1624
+ 2
1625
+ ];
1626
+ preloadSlots.set(token, {
1627
+ ad: ad
1628
+ });
1629
+ return [
1630
+ 2
1631
+ ];
1632
+ }
1633
+ });
1634
+ })();
1635
+ },
1636
+ playPreloaded: function playPreloaded(token) {
1637
+ return _async_to_generator(function() {
1638
+ var slot;
1639
+ return _ts_generator(this, function(_state) {
1640
+ if (destroyed) return [
1641
+ 2,
1642
+ Promise.reject(new Error("Player has been destroyed"))
1643
+ ];
1644
+ slot = preloadSlots.get(token);
1645
+ if (!slot) {
1646
+ return [
1647
+ 2,
1648
+ Promise.reject(new Error("No preloaded ad for token ".concat(token)))
1649
+ ];
1650
+ }
1651
+ preloadSlots.delete(token);
1652
+ assignCurrentAd(slot.ad);
1653
+ return [
1654
+ 2,
1655
+ this.play()
1656
+ ];
1657
+ });
1658
+ }).call(this);
1659
+ },
1660
+ hasPreloaded: function hasPreloaded(token) {
1661
+ return preloadSlots.has(token);
1662
+ },
1663
+ cancelPreload: function cancelPreload(token) {
1664
+ preloadSlots.delete(token);
1920
1665
  },
1921
1666
  isAdPlaying: function isAdPlaying() {
1922
1667
  return adPlaying;
1923
1668
  },
1924
1669
  resize: function resize(width, height) {
1670
+ log("Resizing to ".concat(width, "x").concat(height));
1925
1671
  if (adContainerEl) {
1926
1672
  adContainerEl.style.width = "".concat(width, "px");
1927
1673
  adContainerEl.style.height = "".concat(height, "px");
@@ -1941,6 +1687,7 @@ function createVastAdLayer(contentVideo, options) {
1941
1687
  },
1942
1688
  updateOriginalMutedState: function updateOriginalMutedState(muted, volume) {
1943
1689
  var nextVolume = typeof volume === "number" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;
1690
+ log("updateOriginalMutedState: muted=".concat(muted, ", volume=").concat(nextVolume));
1944
1691
  originalMutedState = muted;
1945
1692
  originalVolume = nextVolume;
1946
1693
  },
@@ -1953,6 +1700,7 @@ function createVastAdLayer(contentVideo, options) {
1953
1700
  setAdVolume: function setAdVolume(volume) {
1954
1701
  if (adVideoElement && adPlaying) {
1955
1702
  adVideoElement.volume = Math.max(0, Math.min(1, volume));
1703
+ adVideoElement.muted = volume === 0;
1956
1704
  }
1957
1705
  },
1958
1706
  getAdVolume: function getAdVolume() {
@@ -1962,11 +1710,16 @@ function createVastAdLayer(contentVideo, options) {
1962
1710
  return 1;
1963
1711
  },
1964
1712
  showPlaceholder: function showPlaceholder() {
1965
- if (singleElementMode) return;
1966
- contentVideo.style.opacity = "0";
1967
- contentVideo.style.visibility = "hidden";
1968
1713
  if (!adContainerEl) {
1969
1714
  var _contentVideo_parentElement;
1715
+ var parent = contentVideo.parentElement;
1716
+ if (parent) {
1717
+ var computed = window.getComputedStyle(parent).position;
1718
+ if (computed === "static") {
1719
+ parent.style.position = "relative";
1720
+ parentPositionOverridden = true;
1721
+ }
1722
+ }
1970
1723
  var container = document.createElement("div");
1971
1724
  container.style.position = "absolute";
1972
1725
  container.style.left = "0";
@@ -1977,24 +1730,43 @@ function createVastAdLayer(contentVideo, options) {
1977
1730
  container.style.alignItems = "center";
1978
1731
  container.style.justifyContent = "center";
1979
1732
  container.style.pointerEvents = "none";
1980
- container.style.zIndex = "10";
1733
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1981
1734
  container.style.backgroundColor = "#000";
1735
+ container.style.isolation = "isolate";
1736
+ var countdown = document.createElement("div");
1737
+ countdown.style.position = "absolute";
1738
+ countdown.style.left = "12px";
1739
+ countdown.style.top = "12px";
1740
+ countdown.style.padding = "4px 8px";
1741
+ countdown.style.borderRadius = "4px";
1742
+ countdown.style.background = "rgba(0,0,0,0.75)";
1743
+ countdown.style.color = "#fff";
1744
+ countdown.style.fontFamily = "sans-serif";
1745
+ countdown.style.fontSize = "12px";
1746
+ countdown.style.lineHeight = "1.2";
1747
+ countdown.style.pointerEvents = "none";
1748
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1749
+ countdown.textContent = "Ad";
1750
+ container.appendChild(countdown);
1982
1751
  (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1983
1752
  adContainerEl = container;
1753
+ adCountdownEl = countdown;
1984
1754
  }
1985
1755
  if (adContainerEl) {
1986
1756
  adContainerEl.style.display = "flex";
1757
+ adContainerEl.style.opacity = "1";
1987
1758
  adContainerEl.style.pointerEvents = "auto";
1988
1759
  }
1989
1760
  },
1990
1761
  hidePlaceholder: function hidePlaceholder() {
1991
1762
  if (adContainerEl) {
1992
- adContainerEl.style.display = "none";
1993
- adContainerEl.style.pointerEvents = "none";
1994
- }
1995
- if (!adPlaying) {
1996
- contentVideo.style.visibility = "visible";
1997
- contentVideo.style.opacity = "1";
1763
+ adContainerEl.style.opacity = "0";
1764
+ setTimeout(function() {
1765
+ if (adContainerEl) {
1766
+ adContainerEl.style.display = "none";
1767
+ adContainerEl.style.pointerEvents = "none";
1768
+ }
1769
+ }, 300);
1998
1770
  }
1999
1771
  }
2000
1772
  };
@@ -3059,6 +2831,7 @@ function getBrowserConfigOverrides() {
3059
2831
  return overrides;
3060
2832
  }
3061
2833
  // src/player/StormcloudVideoPlayer.ts
2834
+ var DEBUG_HISTORY_LIMIT = 120;
3062
2835
  var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3063
2836
  function StormcloudVideoPlayer(config) {
3064
2837
  _class_call_check(this, StormcloudVideoPlayer);
@@ -3097,31 +2870,34 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3097
2870
  this.backoffBaseMs = 1e3;
3098
2871
  this.maxBackoffMs = 15e3;
3099
2872
  this.MIN_AD_REMAINING_MS = 15e3;
2873
+ this.adRequestTimeoutMs = 5e3;
2874
+ this.adRequestMaxRetries = 3;
2875
+ this.adRequestRetryBackoffMs = 1500;
3100
2876
  this.preloadedTokens = [];
2877
+ this.debugLogEntries = [];
2878
+ this.scteMarkerHistory = [];
3101
2879
  initializePolyfills();
3102
2880
  var browserOverrides = getBrowserConfigOverrides();
3103
2881
  this.config = _object_spread({}, browserOverrides, config);
3104
2882
  this.video = config.videoElement;
3105
2883
  this.adTransitionGapMs = (_this_config_adTransitionGapMs = this.config.adTransitionGapMs) !== null && _this_config_adTransitionGapMs !== void 0 ? _this_config_adTransitionGapMs : 100;
3106
2884
  logBrowserInfo(config.debugAdTiming);
3107
- this.vastManager = createVastManager(config.debugAdTiming !== void 0 ? {
3108
- debug: !!config.debugAdTiming
3109
- } : {});
3110
2885
  var browserForAdLayer = detectBrowser();
3111
2886
  var isSinglePipeline = browserForAdLayer.isSmartTV || !!this.config.singlePipelineMode;
3112
- this.adLayer = createVastAdLayer(this.video, {
3113
- continueLiveStreamDuringAds: false,
3114
- smartTVMode: isSinglePipeline,
3115
- singleElementMode: isSinglePipeline,
3116
- forceMP4Ads: isSinglePipeline,
2887
+ this.adLayer = createAdStormPlayer(this.video, {
2888
+ licenseKey: this.config.licenseKey || "",
3117
2889
  debug: !!config.debugAdTiming
3118
2890
  });
2891
+ this.adLayer.updateOptions({
2892
+ continueLiveStreamDuringAds: !isSinglePipeline && this.shouldContinueLiveStreamDuringAds()
2893
+ });
3119
2894
  }
3120
2895
  _create_class(StormcloudVideoPlayer, [
3121
2896
  {
3122
2897
  key: "adRequest",
3123
2898
  value: function adRequest(context) {
3124
2899
  return _async_to_generator(function() {
2900
+ var _ref, _ref1, durationSeconds;
3125
2901
  return _ts_generator(this, function(_state) {
3126
2902
  switch(_state.label){
3127
2903
  case 0:
@@ -3129,15 +2905,28 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3129
2905
  2,
3130
2906
  []
3131
2907
  ];
2908
+ durationSeconds = Math.max(1, Math.ceil((_ref = (_ref1 = context === null || context === void 0 ? void 0 : context.remainingBreakSec) !== null && _ref1 !== void 0 ? _ref1 : context === null || context === void 0 ? void 0 : context.breakDurationSec) !== null && _ref !== void 0 ? _ref : 30));
3132
2909
  return [
3133
2910
  4,
3134
- this.vastManager.initialize()
2911
+ this.adLayer.requestAds(String(durationSeconds))
3135
2912
  ];
3136
2913
  case 1:
3137
2914
  _state.sent();
3138
2915
  return [
3139
2916
  2,
3140
- this.vastManager.requestBidsUntilResponse(context)
2917
+ [
2918
+ {
2919
+ bidder: "adstorm-direct",
2920
+ cpm: 0,
2921
+ width: 0,
2922
+ height: 0,
2923
+ adId: "adstorm",
2924
+ impId: "",
2925
+ creativeId: "adstorm",
2926
+ currency: "USD",
2927
+ durationSec: durationSeconds
2928
+ }
2929
+ ]
3141
2930
  ];
3142
2931
  }
3143
2932
  });
@@ -3194,7 +2983,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3194
2983
  2
3195
2984
  ];
3196
2985
  case 3:
3197
- this.hls = new import_hls2.default(_object_spread_props(_object_spread({
2986
+ this.hls = new import_hls.default(_object_spread_props(_object_spread({
3198
2987
  enableWorker: true,
3199
2988
  backBufferLength: 30,
3200
2989
  liveDurationInfinity: true,
@@ -3212,11 +3001,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3212
3001
  nudgeMaxRetry: 3,
3213
3002
  startPosition: -1
3214
3003
  }));
3215
- this.hls.on(import_hls2.default.Events.MEDIA_ATTACHED, function() {
3004
+ this.hls.on(import_hls.default.Events.MEDIA_ATTACHED, function() {
3216
3005
  var _this_hls;
3217
3006
  (_this_hls = _this.hls) === null || _this_hls === void 0 ? void 0 : _this_hls.loadSource(_this.config.src);
3218
3007
  });
3219
- this.hls.on(import_hls2.default.Events.MANIFEST_PARSED, function(_, data) {
3008
+ this.hls.on(import_hls.default.Events.MANIFEST_PARSED, function(_, data) {
3220
3009
  return _async_to_generator(function() {
3221
3010
  var _this_config_minSegmentsBeforePlay, _ref, _this_hls_levels, _this_hls, adBehavior, _this_hls1, minSegments, _this_video_play;
3222
3011
  return _ts_generator(this, function(_state) {
@@ -3278,7 +3067,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3278
3067
  });
3279
3068
  }).call(_this);
3280
3069
  });
3281
- this.hls.on(import_hls2.default.Events.LEVEL_LOADED, function(_evt, data) {
3070
+ this.hls.on(import_hls.default.Events.LEVEL_LOADED, function(_evt, data) {
3282
3071
  if (_this.inAdBreak || _this.pendingAdBreak) {
3283
3072
  return;
3284
3073
  }
@@ -3351,7 +3140,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3351
3140
  }
3352
3141
  }
3353
3142
  });
3354
- this.hls.on(import_hls2.default.Events.FRAG_BUFFERED, function(_evt, data) {
3143
+ this.hls.on(import_hls.default.Events.FRAG_BUFFERED, function(_evt, data) {
3355
3144
  return _async_to_generator(function() {
3356
3145
  var _this, _this_config_minSegmentsBeforePlay, minSegments, _this_video_play;
3357
3146
  return _ts_generator(this, function(_state) {
@@ -3411,7 +3200,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3411
3200
  });
3412
3201
  }).call(_this);
3413
3202
  });
3414
- this.hls.on(import_hls2.default.Events.FRAG_PARSING_METADATA, function(_evt, data) {
3203
+ this.hls.on(import_hls.default.Events.FRAG_PARSING_METADATA, function(_evt, data) {
3415
3204
  var id3Tags = ((data === null || data === void 0 ? void 0 : data.samples) || []).map(function(s) {
3416
3205
  return {
3417
3206
  key: "ID3",
@@ -3423,7 +3212,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3423
3212
  return _this.onId3Tag(tag);
3424
3213
  });
3425
3214
  });
3426
- this.hls.on(import_hls2.default.Events.FRAG_CHANGED, function(_evt, data) {
3215
+ this.hls.on(import_hls.default.Events.FRAG_CHANGED, function(_evt, data) {
3427
3216
  var frag = data === null || data === void 0 ? void 0 : data.frag;
3428
3217
  var tagList = frag === null || frag === void 0 ? void 0 : frag.tagList;
3429
3218
  if (!Array.isArray(tagList)) return;
@@ -3532,14 +3321,14 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3532
3321
  }
3533
3322
  }
3534
3323
  });
3535
- this.hls.on(import_hls2.default.Events.ERROR, function(_evt, data) {
3324
+ this.hls.on(import_hls.default.Events.ERROR, function(_evt, data) {
3536
3325
  if (data === null || data === void 0 ? void 0 : data.fatal) {
3537
3326
  switch(data.type){
3538
- case import_hls2.default.ErrorTypes.NETWORK_ERROR:
3327
+ case import_hls.default.ErrorTypes.NETWORK_ERROR:
3539
3328
  var _this_hls;
3540
3329
  (_this_hls = _this.hls) === null || _this_hls === void 0 ? void 0 : _this_hls.startLoad();
3541
3330
  break;
3542
- case import_hls2.default.ErrorTypes.MEDIA_ERROR:
3331
+ case import_hls.default.ErrorTypes.MEDIA_ERROR:
3543
3332
  var _this_hls1;
3544
3333
  (_this_hls1 = _this.hls) === null || _this_hls1 === void 0 ? void 0 : _this_hls1.recoverMediaError();
3545
3334
  break;
@@ -3593,6 +3382,9 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3593
3382
  errorMessage += ". Caused by: ".concat(causeMessage);
3594
3383
  }
3595
3384
  }
3385
+ _this.pushDebugLog("error", "ad", errorMessage, _object_spread({}, errorPayload ? {
3386
+ payload: errorPayload
3387
+ } : {}));
3596
3388
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
3597
3389
  _this.adLayer.stop().catch(function() {});
3598
3390
  _this.handleAdFailure();
@@ -3631,7 +3423,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3631
3423
  }
3632
3424
  });
3633
3425
  this.adLayer.on("content_resume", function() {
3426
+ var _ref, _ref1;
3427
+ var _this_savedMutedStateBeforeScte, _this_savedMutedStateBeforeScte1;
3634
3428
  var remaining = _this.getRemainingAdMs();
3429
+ var breakMuted = (_ref = (_this_savedMutedStateBeforeScte = _this.savedMutedStateBeforeScte) === null || _this_savedMutedStateBeforeScte === void 0 ? void 0 : _this_savedMutedStateBeforeScte.muted) !== null && _ref !== void 0 ? _ref : _this.adLayer.getOriginalMutedState();
3430
+ var breakVolume = (_ref1 = (_this_savedMutedStateBeforeScte1 = _this.savedMutedStateBeforeScte) === null || _this_savedMutedStateBeforeScte1 === void 0 ? void 0 : _this_savedMutedStateBeforeScte1.volume) !== null && _ref1 !== void 0 ? _ref1 : _this.adLayer.getOriginalVolume();
3635
3431
  if (_this.config.debugAdTiming) {
3636
3432
  console.log("[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, preloadedTokens=%d, pendingNext=%s", _this.inAdBreak, remaining, _this.preloadedTokens.length, !!_this.pendingNextAdBids);
3637
3433
  }
@@ -3646,7 +3442,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3646
3442
  return;
3647
3443
  }
3648
3444
  _this.consecutiveFailures = 0;
3649
- if (!_this.video.muted) {
3445
+ if (!_this.config.disableFiller && !_this.video.muted) {
3650
3446
  _this.video.muted = true;
3651
3447
  _this.video.volume = 0;
3652
3448
  }
@@ -3713,6 +3509,18 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3713
3509
  if (!_this.config.disableFiller) {
3714
3510
  _this.showPlaceholderLayer();
3715
3511
  _this.adLayer.showPlaceholder();
3512
+ } else {
3513
+ _this.adLayer.hidePlaceholder();
3514
+ if (_this.video.muted !== breakMuted) {
3515
+ _this.video.muted = breakMuted;
3516
+ }
3517
+ if (Math.abs(_this.video.volume - breakVolume) > 0.01) {
3518
+ _this.video.volume = breakVolume;
3519
+ }
3520
+ if (_this.video.paused) {
3521
+ var _this_video_play;
3522
+ (_this_video_play = _this.video.play()) === null || _this_video_play === void 0 ? void 0 : _this_video_play.catch(function() {});
3523
+ }
3716
3524
  }
3717
3525
  _this.stopContinuousFetching();
3718
3526
  return;
@@ -4018,6 +3826,13 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
4018
3826
  value: function onScte35Marker(marker) {
4019
3827
  var _this = this;
4020
3828
  if (this.config.disableAds) return;
3829
+ this.pushScteMarker(marker);
3830
+ this.pushDebugLog("info", "scte35", "SCTE-35 marker detected", {
3831
+ type: marker.type,
3832
+ ptsSeconds: marker.ptsSeconds,
3833
+ durationSeconds: marker.durationSeconds,
3834
+ currentTime: this.video.currentTime
3835
+ });
4021
3836
  if (this.config.debugAdTiming) {
4022
3837
  console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:", {
4023
3838
  type: marker.type,
@@ -4440,6 +4255,16 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
4440
4255
  return this.totalAdsInBreak;
4441
4256
  }
4442
4257
  },
4258
+ {
4259
+ key: "getRemainingAdSeconds",
4260
+ value: function getRemainingAdSeconds() {
4261
+ var remainingMs = this.getRemainingAdMs();
4262
+ if (!Number.isFinite(remainingMs) || remainingMs <= 0 || remainingMs === Number.MAX_SAFE_INTEGER) {
4263
+ return 0;
4264
+ }
4265
+ return Math.ceil(remainingMs / 1e3);
4266
+ }
4267
+ },
4443
4268
  {
4444
4269
  key: "isAdPlaying",
4445
4270
  value: function isAdPlaying() {
@@ -5669,7 +5494,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5669
5494
  });
5670
5495
  };
5671
5496
  var onManifestParsedRestore = function onManifestParsedRestore1() {
5672
- hlsRef.off(import_hls2.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5497
+ hlsRef.off(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5673
5498
  if (!_this.inAdBreak && !_this.adLayer.isAdPlaying()) {
5674
5499
  if (videoRef.muted !== savedMuted) videoRef.muted = savedMuted;
5675
5500
  if (Math.abs(videoRef.volume - savedVolume) > 0.01) videoRef.volume = savedVolume;
@@ -5682,7 +5507,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5682
5507
  }
5683
5508
  }
5684
5509
  };
5685
- hlsRef.on(import_hls2.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5510
+ hlsRef.on(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5686
5511
  var pipelineDelayMs = 300;
5687
5512
  if (debugEnabled) {
5688
5513
  console.log("[StormcloudVideoPlayer] Smart TV: waiting ".concat(pipelineDelayMs, "ms for hardware pipeline release before re-attach"));
@@ -5876,6 +5701,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5876
5701
  if (!this.config.debugAdTiming) {
5877
5702
  return;
5878
5703
  }
5704
+ this.pushDebugLog("info", "ad-state", event, extra);
5879
5705
  console.log("[StormcloudVideoPlayer][AdState]", _object_spread({
5880
5706
  event: event,
5881
5707
  timestamp: /* @__PURE__ */ new Date().toISOString(),
@@ -5895,6 +5721,59 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5895
5721
  return Math.max(0, this.expectedAdBreakDurationMs - elapsed);
5896
5722
  }
5897
5723
  },
5724
+ {
5725
+ key: "pushScteMarker",
5726
+ value: function pushScteMarker(marker) {
5727
+ if (!this.config.debugAdTiming) return;
5728
+ this.scteMarkerHistory.push({
5729
+ timestampMs: Date.now(),
5730
+ marker: marker
5731
+ });
5732
+ if (this.scteMarkerHistory.length > DEBUG_HISTORY_LIMIT) {
5733
+ this.scteMarkerHistory = this.scteMarkerHistory.slice(-DEBUG_HISTORY_LIMIT);
5734
+ }
5735
+ }
5736
+ },
5737
+ {
5738
+ key: "pushDebugLog",
5739
+ value: function pushDebugLog(level, category, message, details) {
5740
+ if (!this.config.debugAdTiming) return;
5741
+ this.debugLogEntries.push(_object_spread({
5742
+ timestampMs: Date.now(),
5743
+ level: level,
5744
+ category: category,
5745
+ message: message
5746
+ }, details ? {
5747
+ details: details
5748
+ } : {}));
5749
+ if (this.debugLogEntries.length > DEBUG_HISTORY_LIMIT) {
5750
+ this.debugLogEntries = this.debugLogEntries.slice(-DEBUG_HISTORY_LIMIT);
5751
+ }
5752
+ }
5753
+ },
5754
+ {
5755
+ key: "getRecentScteMarkers",
5756
+ value: function getRecentScteMarkers() {
5757
+ return this.scteMarkerHistory.map(function(entry) {
5758
+ return _object_spread({
5759
+ timestampMs: entry.timestampMs,
5760
+ type: entry.marker.type
5761
+ }, entry.marker.ptsSeconds !== void 0 ? {
5762
+ ptsSeconds: entry.marker.ptsSeconds
5763
+ } : {}, entry.marker.durationSeconds !== void 0 ? {
5764
+ durationSeconds: entry.marker.durationSeconds
5765
+ } : {}, entry.marker.raw !== void 0 ? {
5766
+ raw: entry.marker.raw
5767
+ } : {});
5768
+ });
5769
+ }
5770
+ },
5771
+ {
5772
+ key: "getDebugLogs",
5773
+ value: function getDebugLogs() {
5774
+ return this.debugLogEntries.slice();
5775
+ }
5776
+ },
5898
5777
  {
5899
5778
  key: "toggleMute",
5900
5779
  value: function toggleMute() {
@@ -6140,6 +6019,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
6140
6019
  (_this_hls = this.hls) === null || _this_hls === void 0 ? void 0 : _this_hls.destroy();
6141
6020
  (_this_adLayer = this.adLayer) === null || _this_adLayer === void 0 ? void 0 : _this_adLayer.destroy();
6142
6021
  this.consecutiveFailures = 0;
6022
+ this.debugLogEntries = [];
6023
+ this.scteMarkerHistory = [];
6143
6024
  }
6144
6025
  }
6145
6026
  ]);