stormcloud-video-player 0.8.63 → 0.8.65

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.
@@ -7,6 +7,9 @@ function _array_like_to_array(arr, len) {
7
7
  function _array_with_holes(arr) {
8
8
  if (Array.isArray(arr)) return arr;
9
9
  }
10
+ function _array_without_holes(arr) {
11
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
12
+ }
10
13
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
14
  try {
12
15
  var info = gen[key](arg);
@@ -44,6 +47,11 @@ function _define_property(obj, key, value) {
44
47
  } else obj[key] = value;
45
48
  return obj;
46
49
  }
50
+ function _iterable_to_array(iter) {
51
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
52
+ return Array.from(iter);
53
+ }
54
+ }
47
55
  function _iterable_to_array_limit(arr, i) {
48
56
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
49
57
  if (_i == null) return;
@@ -71,6 +79,9 @@ function _iterable_to_array_limit(arr, i) {
71
79
  function _non_iterable_rest() {
72
80
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
73
81
  }
82
+ function _non_iterable_spread() {
83
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
84
+ }
74
85
  function _object_spread(target) {
75
86
  for(var i = 1; i < arguments.length; i++){
76
87
  var source = arguments[i] != null ? arguments[i] : {};
@@ -86,9 +97,35 @@ function _object_spread(target) {
86
97
  }
87
98
  return target;
88
99
  }
100
+ function ownKeys(object, enumerableOnly) {
101
+ var keys = Object.keys(object);
102
+ if (Object.getOwnPropertySymbols) {
103
+ var symbols = Object.getOwnPropertySymbols(object);
104
+ if (enumerableOnly) {
105
+ symbols = symbols.filter(function(sym) {
106
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
107
+ });
108
+ }
109
+ keys.push.apply(keys, symbols);
110
+ }
111
+ return keys;
112
+ }
113
+ function _object_spread_props(target, source) {
114
+ source = source != null ? source : {};
115
+ if (Object.getOwnPropertyDescriptors) Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
116
+ else {
117
+ ownKeys(Object(source)).forEach(function(key) {
118
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
119
+ });
120
+ }
121
+ return target;
122
+ }
89
123
  function _sliced_to_array(arr, i) {
90
124
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
91
125
  }
126
+ function _to_consumable_array(arr) {
127
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
128
+ }
92
129
  function _ts_generator(thisArg, body) {
93
130
  var f, y, t, _ = {
94
131
  label: 0,
@@ -590,6 +627,7 @@ function parseProgressOffset(offset) {
590
627
  } : void 0;
591
628
  }
592
629
  var MAX_VAST_WRAPPER_DEPTH = 5;
630
+ var VAST_REQUEST_TIMEOUT_MS = 5e3;
593
631
  var BEACON_TIMEOUT_MS = 3e4;
594
632
  var inFlightBeacons = /* @__PURE__ */ new Set();
595
633
  var VAST_ERROR_MEDIA_DISPLAY = 405;
@@ -613,7 +651,7 @@ function toVastMediaErrorCode(error) {
613
651
  }
614
652
  }
615
653
  function createHlsAdPlayer(contentVideo, options) {
616
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
654
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
617
655
  var adPlaying = false;
618
656
  var originalMutedState = false;
619
657
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -645,6 +683,16 @@ function createHlsAdPlayer(contentVideo, options) {
645
683
  var sawDecodedVideoFrame = false;
646
684
  var videoFrameCallbackHandle;
647
685
  var pendingPlayPromise;
686
+ var currentVastTagUrl;
687
+ var funnelContext = {};
688
+ var mediaCandidates = [];
689
+ var mediaCandidateIndex = 0;
690
+ var mediaStartTimerId;
691
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
692
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
693
+ var pendingVastRequests = /* @__PURE__ */ new Set();
694
+ var pendingRequestAbortReason;
695
+ var forcedMuteByAutoplay = false;
648
696
  function createTrackingState() {
649
697
  return {
650
698
  impression: false,
@@ -695,6 +743,77 @@ function createHlsAdPlayer(contentVideo, options) {
695
743
  }
696
744
  }
697
745
  }
746
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
747
+ "ppid",
748
+ "rdid",
749
+ "idtype",
750
+ "is_lat",
751
+ "ifa",
752
+ "idfa",
753
+ "aaid",
754
+ "uid",
755
+ "user_id",
756
+ "userid",
757
+ "device_id",
758
+ "deviceid",
759
+ "ip",
760
+ "ua",
761
+ "gdpr_consent",
762
+ "us_privacy",
763
+ "gpp",
764
+ "addtl_consent",
765
+ "cust_params",
766
+ "email"
767
+ ]);
768
+ function redactUrl(url) {
769
+ if (!url) return url;
770
+ try {
771
+ var parsed = new URL(url);
772
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
773
+ try {
774
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
775
+ var key = _step.value;
776
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
777
+ parsed.searchParams.set(key, "REDACTED");
778
+ }
779
+ }
780
+ } catch (err) {
781
+ _didIteratorError = true;
782
+ _iteratorError = err;
783
+ } finally{
784
+ try {
785
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
786
+ _iterator.return();
787
+ }
788
+ } finally{
789
+ if (_didIteratorError) {
790
+ throw _iteratorError;
791
+ }
792
+ }
793
+ }
794
+ return parsed.toString();
795
+ } catch (unused) {
796
+ return url.split("?")[0];
797
+ }
798
+ }
799
+ function logFunnel(stage) {
800
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
801
+ var payload = _object_spread({
802
+ stage: stage,
803
+ breakId: funnelContext.breakId,
804
+ requestId: funnelContext.requestId,
805
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
806
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
807
+ podIndex: podIndex,
808
+ podSize: podAds.length,
809
+ vastUrl: redactUrl(currentVastTagUrl),
810
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
811
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
812
+ muted: adVideoElement ? adVideoElement.muted : void 0
813
+ }, extra);
814
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
815
+ emit("ad_funnel", payload);
816
+ }
698
817
  function buildTrackingMacroContext() {
699
818
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
700
819
  var _options2_ad;
@@ -734,20 +853,53 @@ function createHlsAdPlayer(contentVideo, options) {
734
853
  urls.forEach(function(url) {
735
854
  try {
736
855
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
856
+ var trackingHost;
857
+ try {
858
+ trackingHost = new URL(trackingUrl).host;
859
+ } catch (unused) {
860
+ logFunnel("tracking_url_invalid", {
861
+ trackingUrl: redactUrl(trackingUrl)
862
+ });
863
+ return;
864
+ }
865
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
866
+ if (unexpanded) {
867
+ logFunnel("tracking_url_unexpanded_macro", {
868
+ trackingHost: trackingHost,
869
+ macros: Array.from(new Set(unexpanded))
870
+ });
871
+ }
737
872
  var img = new Image(1, 1);
738
873
  inFlightBeacons.add(img);
739
874
  var timeoutId;
740
- var release = function release() {
875
+ var release = function release(outcome) {
741
876
  if (timeoutId !== void 0) clearTimeout(timeoutId);
742
877
  img.onload = null;
743
878
  img.onerror = null;
744
879
  inFlightBeacons.delete(img);
880
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
881
+ if (outcome !== "load") {
882
+ logFunnel("tracking_request_settled", {
883
+ reason: outcome,
884
+ trackingHost: trackingHost
885
+ });
886
+ }
887
+ };
888
+ img.onload = function() {
889
+ return release("load");
745
890
  };
746
- img.onload = release;
747
- img.onerror = release;
748
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
891
+ img.onerror = function() {
892
+ return release("error");
893
+ };
894
+ timeoutId = setTimeout(function() {
895
+ return release("timeout");
896
+ }, BEACON_TIMEOUT_MS);
749
897
  img.src = trackingUrl;
750
898
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
899
+ logFunnel("tracking_request_created", {
900
+ trackingHost: trackingHost,
901
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
902
+ });
751
903
  } catch (error) {
752
904
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
753
905
  }
@@ -777,54 +929,80 @@ function createHlsAdPlayer(contentVideo, options) {
777
929
  bitrate: level.bitrate || 5e6
778
930
  };
779
931
  }
780
- function selectBestMediaFile(mediaFiles) {
781
- if (mediaFiles.length === 0) {
782
- throw new Error("No media files available");
783
- }
784
- var firstFile = mediaFiles[0];
785
- if (!firstFile) {
786
- throw new Error("No media files available");
787
- }
788
- if (mediaFiles.length === 1) {
789
- return firstFile;
790
- }
932
+ function getMediaTargetQuality() {
791
933
  var mainQuality = getMainStreamQuality();
792
- if (!mainQuality) {
793
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
794
- return firstFile;
795
- }
796
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
797
- var scoredFiles = mediaFiles.map(function(file) {
798
- var widthDiff = Math.abs(file.width - mainQuality.width);
799
- var heightDiff = Math.abs(file.height - mainQuality.height);
800
- var resolutionDiff = widthDiff + heightDiff;
801
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
802
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
803
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
804
- return {
934
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
935
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
936
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
937
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
938
+ return null;
939
+ }
940
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
941
+ width: containerWidth,
942
+ height: containerHeight,
943
+ bitrate: 5e6
944
+ };
945
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
946
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
947
+ return {
948
+ width: width,
949
+ height: height,
950
+ bitrate: base.bitrate
951
+ };
952
+ }
953
+ function rankMediaCandidates(mediaFiles) {
954
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
955
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
956
+ var target = getMediaTargetQuality();
957
+ var accepted = [];
958
+ mediaFiles.forEach(function(file, index) {
959
+ var isHls = isHlsMediaFile(file);
960
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
961
+ var canPlay = probe.canPlayType(mimeForProbe);
962
+ var playable = isHls ? import_hls.default.isSupported() || canPlay !== "" : canPlay !== "";
963
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
964
+ var details = {
965
+ index: index,
966
+ candidateUrl: file.url,
967
+ candidateType: file.type,
968
+ width: file.width,
969
+ height: file.height,
970
+ bitrate: file.bitrate,
971
+ canPlayType: canPlay,
972
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
973
+ };
974
+ if (!playable) {
975
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
976
+ reason: "rejected",
977
+ why: "cannot_play_type"
978
+ }));
979
+ return;
980
+ }
981
+ var score = 0;
982
+ if (target) {
983
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
984
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
985
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
986
+ }
987
+ accepted.push({
805
988
  file: file,
806
989
  score: score,
807
- resolutionDiff: resolutionDiff,
808
- bitrateDiff: bitrateDiff
809
- };
990
+ insecure: insecure
991
+ });
992
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
993
+ reason: "accepted",
994
+ // Mixed-content media is often auto-upgraded, so it is kept as a last resort.
995
+ why: insecure ? "insecure_http_deprioritized" : "playable",
996
+ score: score
997
+ }));
810
998
  });
811
- scoredFiles.sort(function(a, b) {
999
+ accepted.sort(function(a, b) {
1000
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
812
1001
  return a.score - b.score;
813
1002
  });
814
- var bestMatch = scoredFiles[0];
815
- if (!bestMatch) {
816
- console.log("[HlsAdPlayer] No best match found, using first media file");
817
- return firstFile;
818
- }
819
- console.log("[HlsAdPlayer] Selected media file:", {
820
- url: bestMatch.file.url,
821
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
822
- bitrate: bestMatch.file.bitrate,
823
- score: bestMatch.score,
824
- resolutionDiff: bestMatch.resolutionDiff,
825
- bitrateDiff: bestMatch.bitrateDiff
1003
+ return accepted.map(function(entry) {
1004
+ return entry.file;
826
1005
  });
827
- return bestMatch.file;
828
1006
  }
829
1007
  function isHlsMediaFile(mediaFile) {
830
1008
  var type = mediaFile.type.toLowerCase();
@@ -841,9 +1019,10 @@ function createHlsAdPlayer(contentVideo, options) {
841
1019
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
842
1020
  return type.startsWith("audio/") || url.endsWith(".mp3") || url.endsWith(".aac") || url.endsWith(".m4a") || url.endsWith(".ogg") || url.endsWith(".oga") || url.endsWith(".opus") || url.endsWith(".wav") || url.endsWith(".weba");
843
1021
  }
844
- function collectVideoMediaFiles(linear, verbose) {
1022
+ function collectVideoMediaFiles(linear, verbose, stats) {
845
1023
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
846
1024
  var mediaFiles = [];
1025
+ if (stats) stats.total += mediaFileElements.length;
847
1026
  if (verbose) {
848
1027
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
849
1028
  }
@@ -864,6 +1043,7 @@ function createHlsAdPlayer(contentVideo, options) {
864
1043
  }
865
1044
  var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
866
1045
  if (apiFramework === "VPAID") {
1046
+ if (stats) stats.vpaid++;
867
1047
  if (verbose) {
868
1048
  console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
869
1049
  }
@@ -879,11 +1059,13 @@ function createHlsAdPlayer(contentVideo, options) {
879
1059
  bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
880
1060
  };
881
1061
  if (isAudioMediaFile(mediaFile)) {
1062
+ if (stats) stats.audio++;
882
1063
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
883
1064
  return;
884
1065
  }
885
1066
  var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
886
1067
  if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1068
+ if (stats) stats.audio++;
887
1069
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (degenerate dimensions ").concat(mediaFile.width, "x").concat(mediaFile.height, ', type="').concat(type, '") — likely an audio-only placeholder rendition'));
888
1070
  return;
889
1071
  }
@@ -892,8 +1074,11 @@ function createHlsAdPlayer(contentVideo, options) {
892
1074
  if (verbose) {
893
1075
  console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
894
1076
  }
895
- } else if (verbose) {
896
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1077
+ } else {
1078
+ if (stats) stats.unsupported++;
1079
+ if (verbose) {
1080
+ console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1081
+ }
897
1082
  }
898
1083
  });
899
1084
  return mediaFiles;
@@ -1017,26 +1202,58 @@ function createHlsAdPlayer(contentVideo, options) {
1017
1202
  }
1018
1203
  function parseVastXml(xmlString) {
1019
1204
  try {
1020
- var _adElements_find;
1021
1205
  var xmlDoc = parseXml(xmlString);
1022
1206
  if (!xmlDoc) return {
1023
1207
  type: "empty"
1024
1208
  };
1025
1209
  var root = xmlDoc.documentElement;
1026
1210
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1027
- var adElement = (_adElements_find = adElements.find(function(el) {
1028
- return getAdSequence(el) === void 0;
1029
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1030
- if (!adElement) {
1211
+ if (adElements.length === 0) {
1031
1212
  var _root_getAttribute;
1032
1213
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1033
1214
  return emptyVastResult(root);
1034
1215
  }
1035
- var parsed = parseAdElement(adElement, true);
1036
- if (parsed.type === "wrapper") {
1037
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1216
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1217
+ return getAdSequence(el) === void 0;
1218
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1219
+ return getAdSequence(el) !== void 0;
1220
+ })));
1221
+ var firstEmpty;
1222
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1223
+ try {
1224
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1225
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1226
+ var parsed = parseAdElement(adElement, true);
1227
+ if (parsed.type === "empty") {
1228
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1229
+ continue;
1230
+ }
1231
+ if (index > 0) {
1232
+ logFunnel("vast_ad_fallback", {
1233
+ usedAdIndex: index,
1234
+ adCount: ordered.length
1235
+ });
1236
+ }
1237
+ if (parsed.type === "wrapper") {
1238
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1239
+ }
1240
+ return parsed;
1241
+ }
1242
+ } catch (err) {
1243
+ _didIteratorError = true;
1244
+ _iteratorError = err;
1245
+ } finally{
1246
+ try {
1247
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1248
+ _iterator.return();
1249
+ }
1250
+ } finally{
1251
+ if (_didIteratorError) {
1252
+ throw _iteratorError;
1253
+ }
1254
+ }
1038
1255
  }
1039
- return parsed;
1256
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1040
1257
  } catch (error) {
1041
1258
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1042
1259
  return {
@@ -1082,6 +1299,10 @@ function createHlsAdPlayer(contentVideo, options) {
1082
1299
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1083
1300
  if (adElement.getAttribute("conditionalAd") === "true") {
1084
1301
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1302
+ logFunnel("vast_no_supported_media", {
1303
+ reason: "vpaid_only",
1304
+ conditionalAd: true
1305
+ });
1085
1306
  return {
1086
1307
  type: "empty",
1087
1308
  errorUrls: errorUrls,
@@ -1090,11 +1311,17 @@ function createHlsAdPlayer(contentVideo, options) {
1090
1311
  }
1091
1312
  var linear;
1092
1313
  var mediaFiles = [];
1314
+ var rejectStats = {
1315
+ total: 0,
1316
+ vpaid: 0,
1317
+ audio: 0,
1318
+ unsupported: 0
1319
+ };
1093
1320
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1094
1321
  try {
1095
1322
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1096
1323
  var candidate = _step.value;
1097
- var files = collectVideoMediaFiles(candidate, verbose);
1324
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1098
1325
  if (files.length > 0) {
1099
1326
  linear = candidate;
1100
1327
  mediaFiles = files;
@@ -1117,6 +1344,10 @@ function createHlsAdPlayer(contentVideo, options) {
1117
1344
  }
1118
1345
  if (!linear) {
1119
1346
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1347
+ var reason = rejectStats.total === 0 ? "no_mediafiles" : rejectStats.vpaid > 0 ? "vpaid_only" : rejectStats.audio > 0 ? "audio_only" : "unsupported_type";
1348
+ logFunnel("vast_no_supported_media", _object_spread({
1349
+ reason: reason
1350
+ }, rejectStats));
1120
1351
  return {
1121
1352
  type: "empty",
1122
1353
  errorUrls: errorUrls,
@@ -1148,77 +1379,122 @@ function createHlsAdPlayer(contentVideo, options) {
1148
1379
  function fetchVastXml(vastTagUrl) {
1149
1380
  var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include";
1150
1381
  return _async_to_generator(function() {
1151
- var requestVast, response, error;
1382
+ var controller, timeoutId, requestVast, response, error, error1;
1152
1383
  return _ts_generator(this, function(_state) {
1153
1384
  switch(_state.label){
1154
1385
  case 0:
1386
+ if (destroyed) {
1387
+ throw new Error("VAST request skipped: ad player destroyed");
1388
+ }
1389
+ controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1390
+ if (controller) pendingVastRequests.add(controller);
1391
+ timeoutId = controller ? setTimeout(function() {
1392
+ return controller.abort();
1393
+ }, VAST_REQUEST_TIMEOUT_MS) : void 0;
1155
1394
  requestVast = function requestVast(creds) {
1156
- return fetch(vastTagUrl, {
1395
+ return fetch(vastTagUrl, _object_spread({
1157
1396
  mode: "cors",
1158
1397
  credentials: creds,
1159
1398
  headers: {
1160
1399
  "Accept": "application/xml, text/xml, */*"
1161
1400
  },
1162
1401
  referrerPolicy: "no-referrer-when-downgrade"
1163
- });
1402
+ }, controller ? {
1403
+ signal: controller.signal
1404
+ } : {}));
1164
1405
  };
1165
1406
  _state.label = 1;
1166
1407
  case 1:
1167
1408
  _state.trys.push([
1168
1409
  1,
1169
- 3,
1410
+ 10,
1411
+ 11,
1412
+ 12
1413
+ ]);
1414
+ _state.label = 2;
1415
+ case 2:
1416
+ _state.trys.push([
1417
+ 2,
1418
+ 4,
1170
1419
  ,
1171
- 7
1420
+ 8
1172
1421
  ]);
1173
1422
  return [
1174
1423
  4,
1175
1424
  requestVast(credentials)
1176
1425
  ];
1177
- case 2:
1426
+ case 3:
1178
1427
  response = _state.sent();
1179
1428
  return [
1180
1429
  3,
1181
- 7
1430
+ 8
1182
1431
  ];
1183
- case 3:
1432
+ case 4:
1184
1433
  error = _state.sent();
1185
- if (!(credentials !== "omit")) return [
1434
+ if (!(credentials !== "omit" && !(controller === null || controller === void 0 ? void 0 : controller.signal.aborted))) return [
1186
1435
  3,
1187
- 5
1436
+ 6
1188
1437
  ];
1189
1438
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1439
+ logFunnel("vast_credentials_retry", {
1440
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1441
+ });
1190
1442
  return [
1191
1443
  4,
1192
1444
  requestVast("omit")
1193
1445
  ];
1194
- case 4:
1446
+ case 5:
1195
1447
  response = _state.sent();
1196
1448
  return [
1197
1449
  3,
1198
- 6
1450
+ 7
1199
1451
  ];
1200
- case 5:
1201
- throw error;
1202
1452
  case 6:
1453
+ throw error;
1454
+ case 7:
1203
1455
  return [
1204
1456
  3,
1205
- 7
1457
+ 8
1206
1458
  ];
1207
- case 7:
1459
+ case 8:
1208
1460
  if (!response.ok) {
1209
1461
  throw new Error("Failed to fetch VAST: ".concat(response.statusText));
1210
1462
  }
1211
1463
  return [
1212
- 2,
1464
+ 4,
1213
1465
  response.text()
1214
1466
  ];
1467
+ case 9:
1468
+ return [
1469
+ 2,
1470
+ _state.sent()
1471
+ ];
1472
+ case 10:
1473
+ error1 = _state.sent();
1474
+ if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1475
+ if (pendingRequestAbortReason) {
1476
+ throw new Error("".concat(pendingRequestAbortReason, " (timeout): ").concat(vastTagUrl));
1477
+ }
1478
+ throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1479
+ }
1480
+ throw error1;
1481
+ case 11:
1482
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
1483
+ if (controller) pendingVastRequests.delete(controller);
1484
+ return [
1485
+ 7
1486
+ ];
1487
+ case 12:
1488
+ return [
1489
+ 2
1490
+ ];
1215
1491
  }
1216
1492
  });
1217
1493
  })();
1218
1494
  }
1219
1495
  function fetchAndParseVastAd(_0) {
1220
1496
  return _async_to_generator(function(vastTagUrl) {
1221
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1497
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1222
1498
  var _arguments = arguments;
1223
1499
  return _ts_generator(this, function(_state) {
1224
1500
  switch(_state.label){
@@ -1226,6 +1502,11 @@ function createHlsAdPlayer(contentVideo, options) {
1226
1502
  depth = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : 0, accumulatedTracking = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : createEmptyTrackingUrls(), rules = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : {
1227
1503
  followAdditionalWrappers: true
1228
1504
  };
1505
+ if (destroyed) return [
1506
+ 2,
1507
+ null
1508
+ ];
1509
+ fetchStartedAt = Date.now();
1229
1510
  _state.label = 1;
1230
1511
  case 1:
1231
1512
  _state.trys.push([
@@ -1248,14 +1529,35 @@ function createHlsAdPlayer(contentVideo, options) {
1248
1529
  error = _state.sent();
1249
1530
  if (depth === 0) throw error;
1250
1531
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1251
- fireTrackingPixels(accumulatedTracking.error, {
1252
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1532
+ logFunnel("wrapper_fetch", {
1533
+ reason: "failure",
1534
+ depth: depth,
1535
+ wrapperUrl: redactUrl(vastTagUrl),
1536
+ elapsedMs: Date.now() - fetchStartedAt,
1537
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1253
1538
  });
1539
+ if (!destroyed) {
1540
+ fireTrackingPixels(accumulatedTracking.error, {
1541
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1542
+ });
1543
+ }
1254
1544
  return [
1255
1545
  2,
1256
1546
  null
1257
1547
  ];
1258
1548
  case 4:
1549
+ if (destroyed) return [
1550
+ 2,
1551
+ null
1552
+ ];
1553
+ if (depth > 0) {
1554
+ logFunnel("wrapper_fetch", {
1555
+ reason: "success",
1556
+ depth: depth,
1557
+ wrapperUrl: redactUrl(vastTagUrl),
1558
+ elapsedMs: Date.now() - fetchStartedAt
1559
+ });
1560
+ }
1259
1561
  console.log("[HlsAdPlayer] VAST XML received");
1260
1562
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1261
1563
  parsed = parseVastXml(vastXml);
@@ -1287,6 +1589,9 @@ function createHlsAdPlayer(contentVideo, options) {
1287
1589
  ];
1288
1590
  }
1289
1591
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1592
+ logFunnel("inline_resolved", {
1593
+ depth: depth
1594
+ });
1290
1595
  return [
1291
1596
  2,
1292
1597
  parsed.ad
@@ -1297,7 +1602,7 @@ function createHlsAdPlayer(contentVideo, options) {
1297
1602
  }
1298
1603
  function fetchAndParsePod(vastTagUrl) {
1299
1604
  return _async_to_generator(function() {
1300
- var _root_getAttribute, vastXml, trimmedXml, xmlDoc, root, adElements, _root_getAttribute1, _empty_errorUrls, empty, _empty_errorCode, resolveAd, podElements, buffet, ads, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, adElement, ad, err, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, adElement1, ad1, err;
1605
+ var _root_getAttribute, vastXml, trimmedXml, xmlDoc, root, adElements, _root_getAttribute1, _empty_errorUrls, empty, _empty_errorCode, resolveAd, podElements, buffet, resolveAll, ads, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, ad, err, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, ad1, err;
1301
1606
  return _ts_generator(this, function(_state) {
1302
1607
  switch(_state.label){
1303
1608
  case 0:
@@ -1307,6 +1612,10 @@ function createHlsAdPlayer(contentVideo, options) {
1307
1612
  ];
1308
1613
  case 1:
1309
1614
  vastXml = _state.sent();
1615
+ if (destroyed) return [
1616
+ 2,
1617
+ []
1618
+ ];
1310
1619
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1311
1620
  trimmedXml = vastXml.trim();
1312
1621
  if (trimmedXml.length === 0) {
@@ -1378,6 +1687,13 @@ function createHlsAdPlayer(contentVideo, options) {
1378
1687
  buffet = adElements.filter(function(el) {
1379
1688
  return getAdSequence(el) === void 0;
1380
1689
  });
1690
+ resolveAll = function resolveAll(elements) {
1691
+ return Promise.all(elements.map(function(el) {
1692
+ return resolveAd(el).catch(function() {
1693
+ return null;
1694
+ });
1695
+ }));
1696
+ };
1381
1697
  ads = [];
1382
1698
  if (!(podElements.length === 0)) return [
1383
1699
  3,
@@ -1392,27 +1708,26 @@ function createHlsAdPlayer(contentVideo, options) {
1392
1708
  8,
1393
1709
  9
1394
1710
  ]);
1395
- _iterator = buffet[Symbol.iterator]();
1396
- _state.label = 3;
1711
+ return [
1712
+ 4,
1713
+ resolveAll(buffet)
1714
+ ];
1397
1715
  case 3:
1716
+ _iterator = _state.sent()[Symbol.iterator]();
1717
+ _state.label = 4;
1718
+ case 4:
1398
1719
  if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
1399
1720
  3,
1400
1721
  6
1401
1722
  ];
1402
- adElement = _step.value;
1403
- return [
1404
- 4,
1405
- resolveAd(adElement)
1406
- ];
1407
- case 4:
1408
- ad = _state.sent();
1723
+ ad = _step.value;
1409
1724
  if (ad) ads.push(ad);
1410
1725
  _state.label = 5;
1411
1726
  case 5:
1412
1727
  _iteratorNormalCompletion = true;
1413
1728
  return [
1414
1729
  3,
1415
- 3
1730
+ 4
1416
1731
  ];
1417
1732
  case 6:
1418
1733
  return [
@@ -1455,20 +1770,19 @@ function createHlsAdPlayer(contentVideo, options) {
1455
1770
  20,
1456
1771
  21
1457
1772
  ]);
1458
- _iterator1 = podElements[Symbol.iterator]();
1459
- _state.label = 12;
1773
+ return [
1774
+ 4,
1775
+ resolveAll(podElements)
1776
+ ];
1460
1777
  case 12:
1778
+ _iterator1 = _state.sent()[Symbol.iterator]();
1779
+ _state.label = 13;
1780
+ case 13:
1461
1781
  if (!!(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done)) return [
1462
1782
  3,
1463
1783
  18
1464
1784
  ];
1465
- adElement1 = _step1.value;
1466
- return [
1467
- 4,
1468
- resolveAd(adElement1)
1469
- ];
1470
- case 13:
1471
- ad1 = _state.sent();
1785
+ ad1 = _step1.value;
1472
1786
  _state.label = 14;
1473
1787
  case 14:
1474
1788
  if (!(!ad1 && buffet.length > 0)) return [
@@ -1477,7 +1791,9 @@ function createHlsAdPlayer(contentVideo, options) {
1477
1791
  ];
1478
1792
  return [
1479
1793
  4,
1480
- resolveAd(buffet.shift())
1794
+ resolveAd(buffet.shift()).catch(function() {
1795
+ return null;
1796
+ })
1481
1797
  ];
1482
1798
  case 15:
1483
1799
  ad1 = _state.sent();
@@ -1492,7 +1808,7 @@ function createHlsAdPlayer(contentVideo, options) {
1492
1808
  _iteratorNormalCompletion1 = true;
1493
1809
  return [
1494
1810
  3,
1495
- 12
1811
+ 13
1496
1812
  ];
1497
1813
  case 18:
1498
1814
  return [
@@ -1587,14 +1903,17 @@ function createHlsAdPlayer(contentVideo, options) {
1587
1903
  var progress = currentTime / currentAd.duration;
1588
1904
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1589
1905
  trackingFired.firstQuartile = true;
1906
+ logFunnel("first_quartile");
1590
1907
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1591
1908
  }
1592
1909
  if (progress >= 0.5 && !trackingFired.midpoint) {
1593
1910
  trackingFired.midpoint = true;
1911
+ logFunnel("midpoint");
1594
1912
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1595
1913
  }
1596
1914
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1597
1915
  trackingFired.thirdQuartile = true;
1916
+ logFunnel("third_quartile");
1598
1917
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1599
1918
  }
1600
1919
  };
@@ -1617,6 +1936,16 @@ function createHlsAdPlayer(contentVideo, options) {
1617
1936
  if (!trackingFired.impression) {
1618
1937
  trackingFired.impression = true;
1619
1938
  resolvedAds.add(currentAd);
1939
+ logFunnel("playing", {
1940
+ mutedByAutoplay: forcedMuteByAutoplay,
1941
+ candidateIndex: mediaCandidateIndex
1942
+ });
1943
+ logFunnel("impression_fired", {
1944
+ pixelCount: currentAd.trackingUrls.impression.length
1945
+ });
1946
+ if (currentAd.trackingUrls.impression.length === 0) {
1947
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
1948
+ }
1620
1949
  fireTrackingPixels(currentAd.trackingUrls.impression);
1621
1950
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1622
1951
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1639,6 +1968,7 @@ function createHlsAdPlayer(contentVideo, options) {
1639
1968
  sampleViewability();
1640
1969
  settleViewability();
1641
1970
  trackingFired.complete = true;
1971
+ logFunnel("complete");
1642
1972
  fireTrackingPixels(currentAd.trackingUrls.complete);
1643
1973
  console.log("[HlsAdPlayer] Ad completed");
1644
1974
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1647,16 +1977,41 @@ function createHlsAdPlayer(contentVideo, options) {
1647
1977
  handleAdComplete();
1648
1978
  };
1649
1979
  var onError = function onError(e) {
1980
+ var _adVideoElement_error, _adVideoElement_error1;
1650
1981
  if (!adPlaying) return;
1651
1982
  console.error("[HlsAdPlayer] Ad video error:", e);
1652
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1653
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1654
- return;
1655
- }
1656
- handleAdError();
1983
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
1984
+ logFunnel("media_error", {
1985
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
1986
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
1987
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
1988
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
1989
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
1990
+ vastErrorCode: vastErrorCode
1991
+ });
1992
+ recoverFromAdFailure(vastErrorCode);
1993
+ };
1994
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
1995
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
1996
+ if (!adVideoElement.currentSrc) return;
1997
+ logFunnel("media_event", {
1998
+ reason: event.type,
1999
+ readyState: adVideoElement.readyState,
2000
+ networkState: adVideoElement.networkState,
2001
+ currentSrc: adVideoElement.currentSrc
2002
+ });
1657
2003
  };
1658
2004
  var onVolumeChange = function onVolumeChange() {
1659
2005
  if (!currentAd || !adVideoElement) return;
2006
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2007
+ var userActivation = navigator.userActivation;
2008
+ if (userActivation && !userActivation.isActive) {
2009
+ logFunnel("unexpected_unmute", {
2010
+ paused: adVideoElement.paused
2011
+ });
2012
+ }
2013
+ forcedMuteByAutoplay = false;
2014
+ }
1660
2015
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1661
2016
  if (!trackingFired.start) {
1662
2017
  trackingFired.lastMuted = muted;
@@ -1716,6 +2071,22 @@ function createHlsAdPlayer(contentVideo, options) {
1716
2071
  {
1717
2072
  type: "play",
1718
2073
  handler: onPlay
2074
+ },
2075
+ {
2076
+ type: "stalled",
2077
+ handler: onMediaDiagnostic
2078
+ },
2079
+ {
2080
+ type: "suspend",
2081
+ handler: onMediaDiagnostic
2082
+ },
2083
+ {
2084
+ type: "abort",
2085
+ handler: onMediaDiagnostic
2086
+ },
2087
+ {
2088
+ type: "emptied",
2089
+ handler: onMediaDiagnostic
1719
2090
  }
1720
2091
  ];
1721
2092
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2005,16 +2376,51 @@ function createHlsAdPlayer(contentVideo, options) {
2005
2376
  function settlePendingPlay() {
2006
2377
  pendingPlayPromise = void 0;
2007
2378
  }
2379
+ function toVastPlayErrorCode(error) {
2380
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2381
+ }
2382
+ function failAdPlayback(context, error) {
2383
+ var vastErrorCode = toVastPlayErrorCode(error);
2384
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2385
+ logFunnel("play_failed", {
2386
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2387
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2388
+ vastErrorCode: vastErrorCode
2389
+ });
2390
+ recoverFromAdFailure(vastErrorCode);
2391
+ }
2008
2392
  function startAdPlayback(context) {
2393
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2009
2394
  if (!adVideoElement) return;
2395
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2396
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2397
+ context: context,
2398
+ isConnected: adVideoElement.isConnected,
2399
+ clientWidth: adVideoElement.clientWidth,
2400
+ clientHeight: adVideoElement.clientHeight,
2401
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2402
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2403
+ });
2010
2404
  var playPromise = adVideoElement.play();
2011
2405
  pendingPlayPromise = playPromise;
2012
2406
  playPromise.catch(function(error) {
2013
2407
  if (pendingPlayPromise !== playPromise) {
2014
2408
  return;
2015
2409
  }
2016
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2017
- handleAdError();
2410
+ logFunnel("play_rejected", {
2411
+ context: context,
2412
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2413
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2414
+ });
2415
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2416
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2417
+ originalMutedState = true;
2418
+ forcedMuteByAutoplay = true;
2419
+ adVideoElement.muted = true;
2420
+ startAdPlayback(context, true);
2421
+ return;
2422
+ }
2423
+ failAdPlayback(context, error);
2018
2424
  }).finally(function() {
2019
2425
  if (pendingPlayPromise === playPromise) {
2020
2426
  pendingPlayPromise = void 0;
@@ -2053,17 +2459,109 @@ function createHlsAdPlayer(contentVideo, options) {
2053
2459
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2054
2460
  adVideoElement.muted = originalMutedState;
2055
2461
  }
2462
+ function clearMediaStartTimer() {
2463
+ if (mediaStartTimerId !== void 0) {
2464
+ clearTimeout(mediaStartTimerId);
2465
+ mediaStartTimerId = void 0;
2466
+ }
2467
+ }
2468
+ function startMediaStartTimer() {
2469
+ clearMediaStartTimer();
2470
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2471
+ var startedAt = Date.now();
2472
+ mediaStartTimerId = setTimeout(function() {
2473
+ mediaStartTimerId = void 0;
2474
+ if (!adPlaying || trackingFired.impression) return;
2475
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2476
+ logFunnel("play_resolved_but_never_started", {
2477
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2478
+ elapsedMs: Date.now() - startedAt,
2479
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2480
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2481
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2482
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2483
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2484
+ });
2485
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2486
+ }, MEDIA_START_TIMEOUT_MS);
2487
+ }
2488
+ function resetVideoElementForNextSource() {
2489
+ clearStallWatchdog();
2490
+ if (requiresMediaPipelineResetAfterAds()) {
2491
+ recreateAdVideoElement();
2492
+ setupAdEventListeners();
2493
+ } else {
2494
+ prepareVideoElementForNewSource();
2495
+ }
2496
+ }
2497
+ function tryNextMediaCandidate() {
2498
+ if (!currentAd || trackingFired.impression) return false;
2499
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2500
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2501
+ mediaCandidateIndex++;
2502
+ var next = mediaCandidates[mediaCandidateIndex];
2503
+ if (!next) return false;
2504
+ logFunnel("media_fallback", {
2505
+ failedUrl: failedUrl,
2506
+ nextUrl: next.url,
2507
+ nextType: next.type,
2508
+ candidateIndex: mediaCandidateIndex,
2509
+ candidateCount: mediaCandidates.length
2510
+ });
2511
+ resetVideoElementForNextSource();
2512
+ try {
2513
+ loadMediaCandidate(next);
2514
+ return true;
2515
+ } catch (error) {
2516
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2517
+ return tryNextMediaCandidate();
2518
+ }
2519
+ }
2520
+ function recoverFromAdFailure(vastErrorCode) {
2521
+ clearMediaStartTimer();
2522
+ if (tryNextMediaCandidate()) return;
2523
+ reportCurrentAdError(vastErrorCode);
2524
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2525
+ handleAdError();
2526
+ }
2056
2527
  function loadCurrentAdMedia() {
2057
2528
  if (!adVideoElement || !currentAd) {
2058
2529
  throw new Error("No ad video element or ad to load");
2059
2530
  }
2060
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2531
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2532
+ mediaCandidateIndex = 0;
2533
+ var mediaFile = mediaCandidates[0];
2061
2534
  if (!mediaFile) {
2062
- throw new Error("No media file available for ad");
2535
+ logFunnel("media_unsupported", {
2536
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2537
+ candidates: currentAd.mediaFiles.length
2538
+ });
2539
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2540
+ throw new Error("No media file this browser can play");
2541
+ }
2542
+ try {
2543
+ loadMediaCandidate(mediaFile);
2544
+ } catch (error) {
2545
+ if (tryNextMediaCandidate()) return;
2546
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2547
+ throw error;
2548
+ }
2549
+ }
2550
+ function loadMediaCandidate(mediaFile) {
2551
+ if (!adVideoElement || !currentAd) {
2552
+ throw new Error("No ad video element or ad to load");
2063
2553
  }
2064
2554
  currentAdMediaFile = mediaFile;
2065
2555
  var isHlsAd = isHlsMediaFile(mediaFile);
2556
+ logFunnel("media_selected", {
2557
+ width: mediaFile.width,
2558
+ height: mediaFile.height,
2559
+ bitrate: mediaFile.bitrate,
2560
+ candidateIndex: mediaCandidateIndex,
2561
+ candidates: mediaCandidates.length
2562
+ });
2066
2563
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2564
+ startMediaStartTimer();
2067
2565
  if (isHlsAd && import_hls.default.isSupported()) {
2068
2566
  if (adHls) {
2069
2567
  adHls.destroy();
@@ -2072,6 +2570,9 @@ function createHlsAdPlayer(contentVideo, options) {
2072
2570
  enableWorker: true,
2073
2571
  lowLatencyMode: false
2074
2572
  });
2573
+ logFunnel("media_load", {
2574
+ pipeline: "hls.js"
2575
+ });
2075
2576
  adHls.loadSource(mediaFile.url);
2076
2577
  adHls.attachMedia(adVideoElement);
2077
2578
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2081,10 +2582,24 @@ function createHlsAdPlayer(contentVideo, options) {
2081
2582
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2082
2583
  console.error("[HlsAdPlayer] HLS error:", data);
2083
2584
  if (data.fatal) {
2084
- handleAdError();
2585
+ var _data_response, _data_response1, _data_frag;
2586
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2587
+ logFunnel("hls_fatal", {
2588
+ reason: data.details,
2589
+ errorName: data.type,
2590
+ errorMessage: data.details,
2591
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2592
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2593
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2594
+ vastErrorCode: vastErrorCode
2595
+ });
2596
+ recoverFromAdFailure(vastErrorCode);
2085
2597
  }
2086
2598
  });
2087
2599
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2600
+ logFunnel("media_load", {
2601
+ pipeline: "native-hls"
2602
+ });
2088
2603
  adVideoElement.src = mediaFile.url;
2089
2604
  startAdPlayback("native HLS ad playback");
2090
2605
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2092,45 +2607,47 @@ function createHlsAdPlayer(contentVideo, options) {
2092
2607
  adHls.destroy();
2093
2608
  adHls = void 0;
2094
2609
  }
2610
+ logFunnel("media_load", {
2611
+ pipeline: "progressive"
2612
+ });
2095
2613
  adVideoElement.src = mediaFile.url;
2096
2614
  adVideoElement.load();
2097
2615
  startAdPlayback("progressive ad playback");
2098
2616
  } else {
2617
+ clearMediaStartTimer();
2618
+ logFunnel("media_unsupported", {
2619
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2620
+ });
2099
2621
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2100
2622
  }
2101
2623
  }
2102
2624
  function advanceToNextPodAd() {
2103
- if (podIndex >= podAds.length - 1) {
2104
- return false;
2105
- }
2106
- settleViewability();
2107
- podIndex++;
2108
- currentAd = podAds[podIndex];
2109
- currentAdMediaFile = void 0;
2110
- resetAdTracking();
2111
- if (currentAd) {
2112
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2113
- }
2114
- clearStallWatchdog();
2115
- if (requiresMediaPipelineResetAfterAds()) {
2116
- recreateAdVideoElement();
2117
- setupAdEventListeners();
2118
- } else {
2119
- prepareVideoElementForNewSource();
2120
- }
2121
- try {
2122
- loadCurrentAdMedia();
2123
- emit("pod_ad_started", {
2124
- index: podIndex,
2125
- total: podAds.length
2126
- });
2127
- return true;
2128
- } catch (error) {
2129
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2130
- return false;
2625
+ clearMediaStartTimer();
2626
+ while(podIndex < podAds.length - 1){
2627
+ settleViewability();
2628
+ podIndex++;
2629
+ currentAd = podAds[podIndex];
2630
+ currentAdMediaFile = void 0;
2631
+ resetAdTracking();
2632
+ if (currentAd) {
2633
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2634
+ }
2635
+ resetVideoElementForNextSource();
2636
+ try {
2637
+ loadCurrentAdMedia();
2638
+ emit("pod_ad_started", {
2639
+ index: podIndex,
2640
+ total: podAds.length
2641
+ });
2642
+ return true;
2643
+ } catch (error) {
2644
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2645
+ }
2131
2646
  }
2647
+ return false;
2132
2648
  }
2133
2649
  function clearStallWatchdog() {
2650
+ clearMediaStartTimer();
2134
2651
  if (stallWatchdogId != null) {
2135
2652
  clearInterval(stallWatchdogId);
2136
2653
  stallWatchdogId = void 0;
@@ -2146,11 +2663,10 @@ function createHlsAdPlayer(contentVideo, options) {
2146
2663
  function handleAdStall() {
2147
2664
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2148
2665
  clearStallWatchdog();
2149
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2150
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2151
- return;
2152
- }
2153
- handleAdError();
2666
+ logFunnel("stall", {
2667
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2668
+ });
2669
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2154
2670
  }
2155
2671
  function getDecodedVideoFrameCount(video) {
2156
2672
  try {
@@ -2212,11 +2728,10 @@ function createHlsAdPlayer(contentVideo, options) {
2212
2728
  function handleVideoDecodeFailure() {
2213
2729
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2214
2730
  clearStallWatchdog();
2215
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2216
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2217
- return;
2218
- }
2219
- handleAdError();
2731
+ logFunnel("decode_failure", {
2732
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2733
+ });
2734
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2220
2735
  }
2221
2736
  function startStallWatchdog() {
2222
2737
  clearStallWatchdog();
@@ -2340,6 +2855,15 @@ function createHlsAdPlayer(contentVideo, options) {
2340
2855
  Promise.reject(new Error("Ad already playing"))
2341
2856
  ];
2342
2857
  }
2858
+ if (destroyed) {
2859
+ return [
2860
+ 2,
2861
+ Promise.reject(new Error("Ad player destroyed"))
2862
+ ];
2863
+ }
2864
+ currentVastTagUrl = vastTagUrl;
2865
+ pendingRequestAbortReason = void 0;
2866
+ logFunnel("request_sent");
2343
2867
  _state.label = 1;
2344
2868
  case 1:
2345
2869
  _state.trys.push([
@@ -2374,8 +2898,18 @@ function createHlsAdPlayer(contentVideo, options) {
2374
2898
  ads = _state.sent();
2375
2899
  _state.label = 4;
2376
2900
  case 4:
2901
+ if (destroyed) {
2902
+ return [
2903
+ 2,
2904
+ Promise.reject(new Error("Ad player destroyed"))
2905
+ ];
2906
+ }
2907
+ if (!ads.length && pendingRequestAbortReason) {
2908
+ throw new Error(pendingRequestAbortReason);
2909
+ }
2377
2910
  if (!ads.length) {
2378
2911
  console.warn("[HlsAdPlayer] No ads available from VAST response");
2912
+ logFunnel("no_fill");
2379
2913
  emit("ad_error");
2380
2914
  return [
2381
2915
  2,
@@ -2386,6 +2920,23 @@ function createHlsAdPlayer(contentVideo, options) {
2386
2920
  podIndex = 0;
2387
2921
  currentAd = ads[0];
2388
2922
  currentAdMediaFile = void 0;
2923
+ logFunnel("vast_received", {
2924
+ adCount: ads.length,
2925
+ durations: ads.map(function(ad) {
2926
+ return ad.duration;
2927
+ }),
2928
+ impressionUrls: ads.map(function(ad) {
2929
+ return ad.trackingUrls.impression.length;
2930
+ })
2931
+ });
2932
+ ads.forEach(function(ad, index) {
2933
+ if (ad.trackingUrls.impression.length === 0) {
2934
+ logFunnel("vast_missing_impression", {
2935
+ adIndex: index,
2936
+ missingAdId: ad.id
2937
+ });
2938
+ }
2939
+ });
2389
2940
  console.log("[HlsAdPlayer] Pod parsed: ".concat(ads.length, ' ad(s), first="').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.title, '", duration=').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.duration, "s"));
2390
2941
  return [
2391
2942
  2,
@@ -2394,6 +2945,9 @@ function createHlsAdPlayer(contentVideo, options) {
2394
2945
  case 5:
2395
2946
  error = _state.sent();
2396
2947
  console.error("[HlsAdPlayer] Error requesting ads:", error);
2948
+ logFunnel("request_failed", {
2949
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2950
+ });
2397
2951
  emit("ad_error");
2398
2952
  return [
2399
2953
  2,
@@ -2449,13 +3003,22 @@ function createHlsAdPlayer(contentVideo, options) {
2449
3003
  adContainerEl.style.pointerEvents = "auto";
2450
3004
  }
2451
3005
  emit("content_pause");
2452
- loadCurrentAdMedia();
3006
+ try {
3007
+ loadCurrentAdMedia();
3008
+ } catch (loadError) {
3009
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3010
+ throw loadError;
3011
+ }
3012
+ }
2453
3013
  return [
2454
3014
  2,
2455
3015
  Promise.resolve()
2456
3016
  ];
2457
3017
  } catch (error) {
2458
3018
  console.error("[HlsAdPlayer] Error playing ad:", error);
3019
+ logFunnel("play_failed", {
3020
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3021
+ });
2459
3022
  handleAdError();
2460
3023
  return [
2461
3024
  2,
@@ -2497,6 +3060,9 @@ function createHlsAdPlayer(contentVideo, options) {
2497
3060
  var previousMutedState;
2498
3061
  return _ts_generator(this, function(_state) {
2499
3062
  console.log("[HlsAdPlayer] Stopping ad");
3063
+ if (adPlaying && currentAd && !trackingFired.impression) {
3064
+ logFunnel("stopped_before_start");
3065
+ }
2500
3066
  settleViewability();
2501
3067
  fireNotUsedForUnplayedAds();
2502
3068
  clearStallWatchdog();
@@ -2529,15 +3095,18 @@ function createHlsAdPlayer(contentVideo, options) {
2529
3095
  },
2530
3096
  destroy: function destroy() {
2531
3097
  console.log("[HlsAdPlayer] Destroying");
3098
+ if (adPlaying && currentAd && !trackingFired.impression) {
3099
+ logFunnel("stopped_before_start");
3100
+ }
2532
3101
  settleViewability();
2533
3102
  fireNotUsedForUnplayedAds();
2534
3103
  destroyed = true;
2535
- clearStallWatchdog();
3104
+ pendingRequestAbortReason = "Ad player destroyed";
2536
3105
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2537
3106
  try {
2538
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2539
- var timeoutId = _step.value;
2540
- clearTimeout(timeoutId);
3107
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3108
+ var controller = _step.value;
3109
+ controller.abort();
2541
3110
  }
2542
3111
  } catch (err) {
2543
3112
  _didIteratorError = true;
@@ -2553,6 +3122,28 @@ function createHlsAdPlayer(contentVideo, options) {
2553
3122
  }
2554
3123
  }
2555
3124
  }
3125
+ pendingVastRequests.clear();
3126
+ clearStallWatchdog();
3127
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3128
+ try {
3129
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3130
+ var timeoutId = _step1.value;
3131
+ clearTimeout(timeoutId);
3132
+ }
3133
+ } catch (err) {
3134
+ _didIteratorError1 = true;
3135
+ _iteratorError1 = err;
3136
+ } finally{
3137
+ try {
3138
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3139
+ _iterator1.return();
3140
+ }
3141
+ } finally{
3142
+ if (_didIteratorError1) {
3143
+ throw _iteratorError1;
3144
+ }
3145
+ }
3146
+ }
2556
3147
  pendingTimeouts = [];
2557
3148
  adPlaying = false;
2558
3149
  setAdPlayingFlag(false);
@@ -2572,6 +3163,35 @@ function createHlsAdPlayer(contentVideo, options) {
2572
3163
  isAdPlaying: function isAdPlaying() {
2573
3164
  return adPlaying;
2574
3165
  },
3166
+ setFunnelContext: function setFunnelContext(context) {
3167
+ funnelContext = _object_spread({}, context);
3168
+ },
3169
+ abortPendingRequest: function abortPendingRequest() {
3170
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3171
+ if (pendingVastRequests.size === 0) return;
3172
+ pendingRequestAbortReason = reason;
3173
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3174
+ try {
3175
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3176
+ var controller = _step.value;
3177
+ controller.abort();
3178
+ }
3179
+ } catch (err) {
3180
+ _didIteratorError = true;
3181
+ _iteratorError = err;
3182
+ } finally{
3183
+ try {
3184
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3185
+ _iterator.return();
3186
+ }
3187
+ } finally{
3188
+ if (_didIteratorError) {
3189
+ throw _iteratorError;
3190
+ }
3191
+ }
3192
+ }
3193
+ pendingVastRequests.clear();
3194
+ },
2575
3195
  resize: function resize(width, height) {
2576
3196
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2577
3197
  if (adContainerEl) {
@@ -2607,6 +3227,13 @@ function createHlsAdPlayer(contentVideo, options) {
2607
3227
  if (adVideoElement && adPlaying) {
2608
3228
  var clamped = Math.max(0, Math.min(1, volume));
2609
3229
  adVideoElement.volume = clamped;
3230
+ var userActivation = navigator.userActivation;
3231
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3232
+ logFunnel("unmute_blocked_without_gesture", {
3233
+ requestedVolume: clamped
3234
+ });
3235
+ return;
3236
+ }
2610
3237
  adVideoElement.muted = clamped === 0;
2611
3238
  }
2612
3239
  },