stormcloud-video-player 0.8.64 → 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,
@@ -614,7 +651,7 @@ function toVastMediaErrorCode(error) {
614
651
  }
615
652
  }
616
653
  function createHlsAdPlayer(contentVideo, options) {
617
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
654
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
618
655
  var adPlaying = false;
619
656
  var originalMutedState = false;
620
657
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -646,6 +683,16 @@ function createHlsAdPlayer(contentVideo, options) {
646
683
  var sawDecodedVideoFrame = false;
647
684
  var videoFrameCallbackHandle;
648
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;
649
696
  function createTrackingState() {
650
697
  return {
651
698
  impression: false,
@@ -696,6 +743,77 @@ function createHlsAdPlayer(contentVideo, options) {
696
743
  }
697
744
  }
698
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
+ }
699
817
  function buildTrackingMacroContext() {
700
818
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
701
819
  var _options2_ad;
@@ -735,20 +853,53 @@ function createHlsAdPlayer(contentVideo, options) {
735
853
  urls.forEach(function(url) {
736
854
  try {
737
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
+ }
738
872
  var img = new Image(1, 1);
739
873
  inFlightBeacons.add(img);
740
874
  var timeoutId;
741
- var release = function release() {
875
+ var release = function release(outcome) {
742
876
  if (timeoutId !== void 0) clearTimeout(timeoutId);
743
877
  img.onload = null;
744
878
  img.onerror = null;
745
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");
746
890
  };
747
- img.onload = release;
748
- img.onerror = release;
749
- 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);
750
897
  img.src = trackingUrl;
751
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
+ });
752
903
  } catch (error) {
753
904
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
754
905
  }
@@ -778,54 +929,80 @@ function createHlsAdPlayer(contentVideo, options) {
778
929
  bitrate: level.bitrate || 5e6
779
930
  };
780
931
  }
781
- function selectBestMediaFile(mediaFiles) {
782
- if (mediaFiles.length === 0) {
783
- throw new Error("No media files available");
784
- }
785
- var firstFile = mediaFiles[0];
786
- if (!firstFile) {
787
- throw new Error("No media files available");
788
- }
789
- if (mediaFiles.length === 1) {
790
- return firstFile;
791
- }
932
+ function getMediaTargetQuality() {
792
933
  var mainQuality = getMainStreamQuality();
793
- if (!mainQuality) {
794
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
795
- return firstFile;
796
- }
797
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
798
- var scoredFiles = mediaFiles.map(function(file) {
799
- var widthDiff = Math.abs(file.width - mainQuality.width);
800
- var heightDiff = Math.abs(file.height - mainQuality.height);
801
- var resolutionDiff = widthDiff + heightDiff;
802
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
803
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
804
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
805
- 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({
806
988
  file: file,
807
989
  score: score,
808
- resolutionDiff: resolutionDiff,
809
- bitrateDiff: bitrateDiff
810
- };
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
+ }));
811
998
  });
812
- scoredFiles.sort(function(a, b) {
999
+ accepted.sort(function(a, b) {
1000
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
813
1001
  return a.score - b.score;
814
1002
  });
815
- var bestMatch = scoredFiles[0];
816
- if (!bestMatch) {
817
- console.log("[HlsAdPlayer] No best match found, using first media file");
818
- return firstFile;
819
- }
820
- console.log("[HlsAdPlayer] Selected media file:", {
821
- url: bestMatch.file.url,
822
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
823
- bitrate: bestMatch.file.bitrate,
824
- score: bestMatch.score,
825
- resolutionDiff: bestMatch.resolutionDiff,
826
- bitrateDiff: bestMatch.bitrateDiff
1003
+ return accepted.map(function(entry) {
1004
+ return entry.file;
827
1005
  });
828
- return bestMatch.file;
829
1006
  }
830
1007
  function isHlsMediaFile(mediaFile) {
831
1008
  var type = mediaFile.type.toLowerCase();
@@ -842,9 +1019,10 @@ function createHlsAdPlayer(contentVideo, options) {
842
1019
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
843
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");
844
1021
  }
845
- function collectVideoMediaFiles(linear, verbose) {
1022
+ function collectVideoMediaFiles(linear, verbose, stats) {
846
1023
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
847
1024
  var mediaFiles = [];
1025
+ if (stats) stats.total += mediaFileElements.length;
848
1026
  if (verbose) {
849
1027
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
850
1028
  }
@@ -865,6 +1043,7 @@ function createHlsAdPlayer(contentVideo, options) {
865
1043
  }
866
1044
  var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
867
1045
  if (apiFramework === "VPAID") {
1046
+ if (stats) stats.vpaid++;
868
1047
  if (verbose) {
869
1048
  console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
870
1049
  }
@@ -880,11 +1059,13 @@ function createHlsAdPlayer(contentVideo, options) {
880
1059
  bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
881
1060
  };
882
1061
  if (isAudioMediaFile(mediaFile)) {
1062
+ if (stats) stats.audio++;
883
1063
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
884
1064
  return;
885
1065
  }
886
1066
  var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
887
1067
  if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1068
+ if (stats) stats.audio++;
888
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'));
889
1070
  return;
890
1071
  }
@@ -893,8 +1074,11 @@ function createHlsAdPlayer(contentVideo, options) {
893
1074
  if (verbose) {
894
1075
  console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
895
1076
  }
896
- } else if (verbose) {
897
- 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
+ }
898
1082
  }
899
1083
  });
900
1084
  return mediaFiles;
@@ -1018,26 +1202,58 @@ function createHlsAdPlayer(contentVideo, options) {
1018
1202
  }
1019
1203
  function parseVastXml(xmlString) {
1020
1204
  try {
1021
- var _adElements_find;
1022
1205
  var xmlDoc = parseXml(xmlString);
1023
1206
  if (!xmlDoc) return {
1024
1207
  type: "empty"
1025
1208
  };
1026
1209
  var root = xmlDoc.documentElement;
1027
1210
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1028
- var adElement = (_adElements_find = adElements.find(function(el) {
1029
- return getAdSequence(el) === void 0;
1030
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1031
- if (!adElement) {
1211
+ if (adElements.length === 0) {
1032
1212
  var _root_getAttribute;
1033
1213
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1034
1214
  return emptyVastResult(root);
1035
1215
  }
1036
- var parsed = parseAdElement(adElement, true);
1037
- if (parsed.type === "wrapper") {
1038
- 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
+ }
1039
1255
  }
1040
- return parsed;
1256
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1041
1257
  } catch (error) {
1042
1258
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1043
1259
  return {
@@ -1083,6 +1299,10 @@ function createHlsAdPlayer(contentVideo, options) {
1083
1299
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1084
1300
  if (adElement.getAttribute("conditionalAd") === "true") {
1085
1301
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1302
+ logFunnel("vast_no_supported_media", {
1303
+ reason: "vpaid_only",
1304
+ conditionalAd: true
1305
+ });
1086
1306
  return {
1087
1307
  type: "empty",
1088
1308
  errorUrls: errorUrls,
@@ -1091,11 +1311,17 @@ function createHlsAdPlayer(contentVideo, options) {
1091
1311
  }
1092
1312
  var linear;
1093
1313
  var mediaFiles = [];
1314
+ var rejectStats = {
1315
+ total: 0,
1316
+ vpaid: 0,
1317
+ audio: 0,
1318
+ unsupported: 0
1319
+ };
1094
1320
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1095
1321
  try {
1096
1322
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1097
1323
  var candidate = _step.value;
1098
- var files = collectVideoMediaFiles(candidate, verbose);
1324
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1099
1325
  if (files.length > 0) {
1100
1326
  linear = candidate;
1101
1327
  mediaFiles = files;
@@ -1118,6 +1344,10 @@ function createHlsAdPlayer(contentVideo, options) {
1118
1344
  }
1119
1345
  if (!linear) {
1120
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));
1121
1351
  return {
1122
1352
  type: "empty",
1123
1353
  errorUrls: errorUrls,
@@ -1153,7 +1383,11 @@ function createHlsAdPlayer(contentVideo, options) {
1153
1383
  return _ts_generator(this, function(_state) {
1154
1384
  switch(_state.label){
1155
1385
  case 0:
1386
+ if (destroyed) {
1387
+ throw new Error("VAST request skipped: ad player destroyed");
1388
+ }
1156
1389
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1390
+ if (controller) pendingVastRequests.add(controller);
1157
1391
  timeoutId = controller ? setTimeout(function() {
1158
1392
  return controller.abort();
1159
1393
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
@@ -1202,6 +1436,9 @@ function createHlsAdPlayer(contentVideo, options) {
1202
1436
  6
1203
1437
  ];
1204
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
+ });
1205
1442
  return [
1206
1443
  4,
1207
1444
  requestVast("omit")
@@ -1235,11 +1472,15 @@ function createHlsAdPlayer(contentVideo, options) {
1235
1472
  case 10:
1236
1473
  error1 = _state.sent();
1237
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
+ }
1238
1478
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1239
1479
  }
1240
1480
  throw error1;
1241
1481
  case 11:
1242
1482
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1483
+ if (controller) pendingVastRequests.delete(controller);
1243
1484
  return [
1244
1485
  7
1245
1486
  ];
@@ -1253,7 +1494,7 @@ function createHlsAdPlayer(contentVideo, options) {
1253
1494
  }
1254
1495
  function fetchAndParseVastAd(_0) {
1255
1496
  return _async_to_generator(function(vastTagUrl) {
1256
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1497
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1257
1498
  var _arguments = arguments;
1258
1499
  return _ts_generator(this, function(_state) {
1259
1500
  switch(_state.label){
@@ -1261,6 +1502,11 @@ function createHlsAdPlayer(contentVideo, options) {
1261
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] : {
1262
1503
  followAdditionalWrappers: true
1263
1504
  };
1505
+ if (destroyed) return [
1506
+ 2,
1507
+ null
1508
+ ];
1509
+ fetchStartedAt = Date.now();
1264
1510
  _state.label = 1;
1265
1511
  case 1:
1266
1512
  _state.trys.push([
@@ -1283,14 +1529,35 @@ function createHlsAdPlayer(contentVideo, options) {
1283
1529
  error = _state.sent();
1284
1530
  if (depth === 0) throw error;
1285
1531
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1286
- fireTrackingPixels(accumulatedTracking.error, {
1287
- 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
1288
1538
  });
1539
+ if (!destroyed) {
1540
+ fireTrackingPixels(accumulatedTracking.error, {
1541
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1542
+ });
1543
+ }
1289
1544
  return [
1290
1545
  2,
1291
1546
  null
1292
1547
  ];
1293
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
+ }
1294
1561
  console.log("[HlsAdPlayer] VAST XML received");
1295
1562
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1296
1563
  parsed = parseVastXml(vastXml);
@@ -1322,6 +1589,9 @@ function createHlsAdPlayer(contentVideo, options) {
1322
1589
  ];
1323
1590
  }
1324
1591
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1592
+ logFunnel("inline_resolved", {
1593
+ depth: depth
1594
+ });
1325
1595
  return [
1326
1596
  2,
1327
1597
  parsed.ad
@@ -1342,6 +1612,10 @@ function createHlsAdPlayer(contentVideo, options) {
1342
1612
  ];
1343
1613
  case 1:
1344
1614
  vastXml = _state.sent();
1615
+ if (destroyed) return [
1616
+ 2,
1617
+ []
1618
+ ];
1345
1619
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1346
1620
  trimmedXml = vastXml.trim();
1347
1621
  if (trimmedXml.length === 0) {
@@ -1629,14 +1903,17 @@ function createHlsAdPlayer(contentVideo, options) {
1629
1903
  var progress = currentTime / currentAd.duration;
1630
1904
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1631
1905
  trackingFired.firstQuartile = true;
1906
+ logFunnel("first_quartile");
1632
1907
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1633
1908
  }
1634
1909
  if (progress >= 0.5 && !trackingFired.midpoint) {
1635
1910
  trackingFired.midpoint = true;
1911
+ logFunnel("midpoint");
1636
1912
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1637
1913
  }
1638
1914
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1639
1915
  trackingFired.thirdQuartile = true;
1916
+ logFunnel("third_quartile");
1640
1917
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1641
1918
  }
1642
1919
  };
@@ -1659,6 +1936,16 @@ function createHlsAdPlayer(contentVideo, options) {
1659
1936
  if (!trackingFired.impression) {
1660
1937
  trackingFired.impression = true;
1661
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
+ }
1662
1949
  fireTrackingPixels(currentAd.trackingUrls.impression);
1663
1950
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1664
1951
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1681,6 +1968,7 @@ function createHlsAdPlayer(contentVideo, options) {
1681
1968
  sampleViewability();
1682
1969
  settleViewability();
1683
1970
  trackingFired.complete = true;
1971
+ logFunnel("complete");
1684
1972
  fireTrackingPixels(currentAd.trackingUrls.complete);
1685
1973
  console.log("[HlsAdPlayer] Ad completed");
1686
1974
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1689,16 +1977,41 @@ function createHlsAdPlayer(contentVideo, options) {
1689
1977
  handleAdComplete();
1690
1978
  };
1691
1979
  var onError = function onError(e) {
1980
+ var _adVideoElement_error, _adVideoElement_error1;
1692
1981
  if (!adPlaying) return;
1693
1982
  console.error("[HlsAdPlayer] Ad video error:", e);
1694
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1695
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1696
- return;
1697
- }
1698
- 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
+ });
1699
2003
  };
1700
2004
  var onVolumeChange = function onVolumeChange() {
1701
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
+ }
1702
2015
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1703
2016
  if (!trackingFired.start) {
1704
2017
  trackingFired.lastMuted = muted;
@@ -1758,6 +2071,22 @@ function createHlsAdPlayer(contentVideo, options) {
1758
2071
  {
1759
2072
  type: "play",
1760
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
1761
2090
  }
1762
2091
  ];
1763
2092
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2047,16 +2376,51 @@ function createHlsAdPlayer(contentVideo, options) {
2047
2376
  function settlePendingPlay() {
2048
2377
  pendingPlayPromise = void 0;
2049
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
+ }
2050
2392
  function startAdPlayback(context) {
2393
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2051
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
+ });
2052
2404
  var playPromise = adVideoElement.play();
2053
2405
  pendingPlayPromise = playPromise;
2054
2406
  playPromise.catch(function(error) {
2055
2407
  if (pendingPlayPromise !== playPromise) {
2056
2408
  return;
2057
2409
  }
2058
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2059
- 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);
2060
2424
  }).finally(function() {
2061
2425
  if (pendingPlayPromise === playPromise) {
2062
2426
  pendingPlayPromise = void 0;
@@ -2095,17 +2459,109 @@ function createHlsAdPlayer(contentVideo, options) {
2095
2459
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2096
2460
  adVideoElement.muted = originalMutedState;
2097
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
+ }
2098
2527
  function loadCurrentAdMedia() {
2099
2528
  if (!adVideoElement || !currentAd) {
2100
2529
  throw new Error("No ad video element or ad to load");
2101
2530
  }
2102
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2531
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2532
+ mediaCandidateIndex = 0;
2533
+ var mediaFile = mediaCandidates[0];
2103
2534
  if (!mediaFile) {
2104
- 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");
2105
2553
  }
2106
2554
  currentAdMediaFile = mediaFile;
2107
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
+ });
2108
2563
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2564
+ startMediaStartTimer();
2109
2565
  if (isHlsAd && import_hls.default.isSupported()) {
2110
2566
  if (adHls) {
2111
2567
  adHls.destroy();
@@ -2114,6 +2570,9 @@ function createHlsAdPlayer(contentVideo, options) {
2114
2570
  enableWorker: true,
2115
2571
  lowLatencyMode: false
2116
2572
  });
2573
+ logFunnel("media_load", {
2574
+ pipeline: "hls.js"
2575
+ });
2117
2576
  adHls.loadSource(mediaFile.url);
2118
2577
  adHls.attachMedia(adVideoElement);
2119
2578
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2123,10 +2582,24 @@ function createHlsAdPlayer(contentVideo, options) {
2123
2582
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2124
2583
  console.error("[HlsAdPlayer] HLS error:", data);
2125
2584
  if (data.fatal) {
2126
- 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);
2127
2597
  }
2128
2598
  });
2129
2599
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2600
+ logFunnel("media_load", {
2601
+ pipeline: "native-hls"
2602
+ });
2130
2603
  adVideoElement.src = mediaFile.url;
2131
2604
  startAdPlayback("native HLS ad playback");
2132
2605
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2134,45 +2607,47 @@ function createHlsAdPlayer(contentVideo, options) {
2134
2607
  adHls.destroy();
2135
2608
  adHls = void 0;
2136
2609
  }
2610
+ logFunnel("media_load", {
2611
+ pipeline: "progressive"
2612
+ });
2137
2613
  adVideoElement.src = mediaFile.url;
2138
2614
  adVideoElement.load();
2139
2615
  startAdPlayback("progressive ad playback");
2140
2616
  } else {
2617
+ clearMediaStartTimer();
2618
+ logFunnel("media_unsupported", {
2619
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2620
+ });
2141
2621
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2142
2622
  }
2143
2623
  }
2144
2624
  function advanceToNextPodAd() {
2145
- if (podIndex >= podAds.length - 1) {
2146
- return false;
2147
- }
2148
- settleViewability();
2149
- podIndex++;
2150
- currentAd = podAds[podIndex];
2151
- currentAdMediaFile = void 0;
2152
- resetAdTracking();
2153
- if (currentAd) {
2154
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2155
- }
2156
- clearStallWatchdog();
2157
- if (requiresMediaPipelineResetAfterAds()) {
2158
- recreateAdVideoElement();
2159
- setupAdEventListeners();
2160
- } else {
2161
- prepareVideoElementForNewSource();
2162
- }
2163
- try {
2164
- loadCurrentAdMedia();
2165
- emit("pod_ad_started", {
2166
- index: podIndex,
2167
- total: podAds.length
2168
- });
2169
- return true;
2170
- } catch (error) {
2171
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2172
- 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
+ }
2173
2646
  }
2647
+ return false;
2174
2648
  }
2175
2649
  function clearStallWatchdog() {
2650
+ clearMediaStartTimer();
2176
2651
  if (stallWatchdogId != null) {
2177
2652
  clearInterval(stallWatchdogId);
2178
2653
  stallWatchdogId = void 0;
@@ -2188,11 +2663,10 @@ function createHlsAdPlayer(contentVideo, options) {
2188
2663
  function handleAdStall() {
2189
2664
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2190
2665
  clearStallWatchdog();
2191
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2192
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2193
- return;
2194
- }
2195
- handleAdError();
2666
+ logFunnel("stall", {
2667
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2668
+ });
2669
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2196
2670
  }
2197
2671
  function getDecodedVideoFrameCount(video) {
2198
2672
  try {
@@ -2254,11 +2728,10 @@ function createHlsAdPlayer(contentVideo, options) {
2254
2728
  function handleVideoDecodeFailure() {
2255
2729
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2256
2730
  clearStallWatchdog();
2257
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2258
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2259
- return;
2260
- }
2261
- handleAdError();
2731
+ logFunnel("decode_failure", {
2732
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2733
+ });
2734
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2262
2735
  }
2263
2736
  function startStallWatchdog() {
2264
2737
  clearStallWatchdog();
@@ -2382,6 +2855,15 @@ function createHlsAdPlayer(contentVideo, options) {
2382
2855
  Promise.reject(new Error("Ad already playing"))
2383
2856
  ];
2384
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");
2385
2867
  _state.label = 1;
2386
2868
  case 1:
2387
2869
  _state.trys.push([
@@ -2416,8 +2898,18 @@ function createHlsAdPlayer(contentVideo, options) {
2416
2898
  ads = _state.sent();
2417
2899
  _state.label = 4;
2418
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
+ }
2419
2910
  if (!ads.length) {
2420
2911
  console.warn("[HlsAdPlayer] No ads available from VAST response");
2912
+ logFunnel("no_fill");
2421
2913
  emit("ad_error");
2422
2914
  return [
2423
2915
  2,
@@ -2428,6 +2920,23 @@ function createHlsAdPlayer(contentVideo, options) {
2428
2920
  podIndex = 0;
2429
2921
  currentAd = ads[0];
2430
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
+ });
2431
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"));
2432
2941
  return [
2433
2942
  2,
@@ -2436,6 +2945,9 @@ function createHlsAdPlayer(contentVideo, options) {
2436
2945
  case 5:
2437
2946
  error = _state.sent();
2438
2947
  console.error("[HlsAdPlayer] Error requesting ads:", error);
2948
+ logFunnel("request_failed", {
2949
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2950
+ });
2439
2951
  emit("ad_error");
2440
2952
  return [
2441
2953
  2,
@@ -2491,13 +3003,22 @@ function createHlsAdPlayer(contentVideo, options) {
2491
3003
  adContainerEl.style.pointerEvents = "auto";
2492
3004
  }
2493
3005
  emit("content_pause");
2494
- loadCurrentAdMedia();
3006
+ try {
3007
+ loadCurrentAdMedia();
3008
+ } catch (loadError) {
3009
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3010
+ throw loadError;
3011
+ }
3012
+ }
2495
3013
  return [
2496
3014
  2,
2497
3015
  Promise.resolve()
2498
3016
  ];
2499
3017
  } catch (error) {
2500
3018
  console.error("[HlsAdPlayer] Error playing ad:", error);
3019
+ logFunnel("play_failed", {
3020
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3021
+ });
2501
3022
  handleAdError();
2502
3023
  return [
2503
3024
  2,
@@ -2539,6 +3060,9 @@ function createHlsAdPlayer(contentVideo, options) {
2539
3060
  var previousMutedState;
2540
3061
  return _ts_generator(this, function(_state) {
2541
3062
  console.log("[HlsAdPlayer] Stopping ad");
3063
+ if (adPlaying && currentAd && !trackingFired.impression) {
3064
+ logFunnel("stopped_before_start");
3065
+ }
2542
3066
  settleViewability();
2543
3067
  fireNotUsedForUnplayedAds();
2544
3068
  clearStallWatchdog();
@@ -2571,15 +3095,18 @@ function createHlsAdPlayer(contentVideo, options) {
2571
3095
  },
2572
3096
  destroy: function destroy() {
2573
3097
  console.log("[HlsAdPlayer] Destroying");
3098
+ if (adPlaying && currentAd && !trackingFired.impression) {
3099
+ logFunnel("stopped_before_start");
3100
+ }
2574
3101
  settleViewability();
2575
3102
  fireNotUsedForUnplayedAds();
2576
3103
  destroyed = true;
2577
- clearStallWatchdog();
3104
+ pendingRequestAbortReason = "Ad player destroyed";
2578
3105
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2579
3106
  try {
2580
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2581
- var timeoutId = _step.value;
2582
- 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();
2583
3110
  }
2584
3111
  } catch (err) {
2585
3112
  _didIteratorError = true;
@@ -2595,6 +3122,28 @@ function createHlsAdPlayer(contentVideo, options) {
2595
3122
  }
2596
3123
  }
2597
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
+ }
2598
3147
  pendingTimeouts = [];
2599
3148
  adPlaying = false;
2600
3149
  setAdPlayingFlag(false);
@@ -2614,6 +3163,35 @@ function createHlsAdPlayer(contentVideo, options) {
2614
3163
  isAdPlaying: function isAdPlaying() {
2615
3164
  return adPlaying;
2616
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
+ },
2617
3195
  resize: function resize(width, height) {
2618
3196
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2619
3197
  if (adContainerEl) {
@@ -2649,6 +3227,13 @@ function createHlsAdPlayer(contentVideo, options) {
2649
3227
  if (adVideoElement && adPlaying) {
2650
3228
  var clamped = Math.max(0, Math.min(1, volume));
2651
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
+ }
2652
3237
  adVideoElement.muted = clamped === 0;
2653
3238
  }
2654
3239
  },