stormcloud-video-player 0.8.64 → 0.8.66

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.
@@ -284,26 +284,6 @@ function _ts_generator(thisArg, body) {
284
284
  };
285
285
  }
286
286
  }
287
- function _ts_values(o) {
288
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
289
- if (m) {
290
- return m.call(o);
291
- }
292
- if (o && typeof o.length === "number") {
293
- return {
294
- next: function() {
295
- if (o && i >= o.length) {
296
- o = void 0;
297
- }
298
- return {
299
- value: o && o[i++],
300
- done: !o
301
- };
302
- }
303
- };
304
- }
305
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
306
- }
307
287
  function _type_of(obj) {
308
288
  "@swc/helpers - typeof";
309
289
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
@@ -761,7 +741,7 @@ function toVastMediaErrorCode(error) {
761
741
  }
762
742
  }
763
743
  function createHlsAdPlayer(contentVideo, options) {
764
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
744
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
765
745
  var adPlaying = false;
766
746
  var originalMutedState = false;
767
747
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -793,6 +773,18 @@ function createHlsAdPlayer(contentVideo, options) {
793
773
  var sawDecodedVideoFrame = false;
794
774
  var videoFrameCallbackHandle;
795
775
  var pendingPlayPromise;
776
+ var currentVastTagUrl;
777
+ var funnelContext = {};
778
+ var mediaProbe;
779
+ var lastPodAdElementCount = 0;
780
+ var mediaCandidates = [];
781
+ var mediaCandidateIndex = 0;
782
+ var mediaStartTimerId;
783
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
784
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
785
+ var pendingVastRequests = /* @__PURE__ */ new Set();
786
+ var pendingRequestAbortReason;
787
+ var forcedMuteByAutoplay = false;
796
788
  function createTrackingState() {
797
789
  return {
798
790
  impression: false,
@@ -843,6 +835,78 @@ function createHlsAdPlayer(contentVideo, options) {
843
835
  }
844
836
  }
845
837
  }
838
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
839
+ "ppid",
840
+ "rdid",
841
+ "idtype",
842
+ "is_lat",
843
+ "ifa",
844
+ "idfa",
845
+ "aaid",
846
+ "uid",
847
+ "user_id",
848
+ "userid",
849
+ "device_id",
850
+ "deviceid",
851
+ "ip",
852
+ "ua",
853
+ "gdpr_consent",
854
+ "us_privacy",
855
+ "gpp",
856
+ "addtl_consent",
857
+ "cust_params",
858
+ "email"
859
+ ]);
860
+ function redactUrl(url) {
861
+ if (!url) return url;
862
+ try {
863
+ var parsed = new URL(url);
864
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
865
+ try {
866
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
867
+ var key = _step.value;
868
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
869
+ parsed.searchParams.set(key, "REDACTED");
870
+ }
871
+ }
872
+ } catch (err) {
873
+ _didIteratorError = true;
874
+ _iteratorError = err;
875
+ } finally{
876
+ try {
877
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
878
+ _iterator.return();
879
+ }
880
+ } finally{
881
+ if (_didIteratorError) {
882
+ throw _iteratorError;
883
+ }
884
+ }
885
+ }
886
+ return parsed.toString();
887
+ } catch (unused) {
888
+ return url.split("?")[0];
889
+ }
890
+ }
891
+ function logFunnel(stage) {
892
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
893
+ var payload = _object_spread({
894
+ stage: stage,
895
+ breakId: funnelContext.breakId,
896
+ requestId: funnelContext.requestId,
897
+ controllerId: funnelContext.controllerId,
898
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
899
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
900
+ podIndex: podIndex,
901
+ podSize: podAds.length,
902
+ vastUrl: redactUrl(currentVastTagUrl),
903
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
904
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
905
+ muted: adVideoElement ? adVideoElement.muted : void 0
906
+ }, extra);
907
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
908
+ emit("ad_funnel", payload);
909
+ }
846
910
  function buildTrackingMacroContext() {
847
911
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
848
912
  var _options2_ad;
@@ -882,20 +946,53 @@ function createHlsAdPlayer(contentVideo, options) {
882
946
  urls.forEach(function(url) {
883
947
  try {
884
948
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
949
+ var trackingHost;
950
+ try {
951
+ trackingHost = new URL(trackingUrl).host;
952
+ } catch (unused) {
953
+ logFunnel("tracking_url_invalid", {
954
+ trackingUrl: redactUrl(trackingUrl)
955
+ });
956
+ return;
957
+ }
958
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
959
+ if (unexpanded) {
960
+ logFunnel("tracking_url_unexpanded_macro", {
961
+ trackingHost: trackingHost,
962
+ macros: Array.from(new Set(unexpanded))
963
+ });
964
+ }
885
965
  var img = new Image(1, 1);
886
966
  inFlightBeacons.add(img);
887
967
  var timeoutId;
888
- var release = function release() {
968
+ var release = function release(outcome) {
889
969
  if (timeoutId !== void 0) clearTimeout(timeoutId);
890
970
  img.onload = null;
891
971
  img.onerror = null;
892
972
  inFlightBeacons.delete(img);
973
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
974
+ if (outcome !== "load") {
975
+ logFunnel("tracking_request_settled", {
976
+ reason: outcome,
977
+ trackingHost: trackingHost
978
+ });
979
+ }
980
+ };
981
+ img.onload = function() {
982
+ return release("load");
893
983
  };
894
- img.onload = release;
895
- img.onerror = release;
896
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
984
+ img.onerror = function() {
985
+ return release("error");
986
+ };
987
+ timeoutId = setTimeout(function() {
988
+ return release("timeout");
989
+ }, BEACON_TIMEOUT_MS);
897
990
  img.src = trackingUrl;
898
991
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
992
+ logFunnel("tracking_request_created", {
993
+ trackingHost: trackingHost,
994
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
995
+ });
899
996
  } catch (error) {
900
997
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
901
998
  }
@@ -925,54 +1022,79 @@ function createHlsAdPlayer(contentVideo, options) {
925
1022
  bitrate: level.bitrate || 5e6
926
1023
  };
927
1024
  }
928
- function selectBestMediaFile(mediaFiles) {
929
- if (mediaFiles.length === 0) {
930
- throw new Error("No media files available");
931
- }
932
- var firstFile = mediaFiles[0];
933
- if (!firstFile) {
934
- throw new Error("No media files available");
935
- }
936
- if (mediaFiles.length === 1) {
937
- return firstFile;
938
- }
1025
+ function getMediaTargetQuality() {
939
1026
  var mainQuality = getMainStreamQuality();
940
- if (!mainQuality) {
941
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
942
- return firstFile;
943
- }
944
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
945
- var scoredFiles = mediaFiles.map(function(file) {
946
- var widthDiff = Math.abs(file.width - mainQuality.width);
947
- var heightDiff = Math.abs(file.height - mainQuality.height);
948
- var resolutionDiff = widthDiff + heightDiff;
949
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
950
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
951
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
952
- return {
1027
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1028
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1029
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1030
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1031
+ return null;
1032
+ }
1033
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1034
+ width: containerWidth,
1035
+ height: containerHeight,
1036
+ bitrate: 5e6
1037
+ };
1038
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1039
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1040
+ return {
1041
+ width: width,
1042
+ height: height,
1043
+ bitrate: base.bitrate
1044
+ };
1045
+ }
1046
+ function rankMediaCandidates(mediaFiles) {
1047
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1048
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1049
+ var target = getMediaTargetQuality();
1050
+ var accepted = [];
1051
+ mediaFiles.forEach(function(file, index) {
1052
+ var isHls = isHlsMediaFile(file);
1053
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1054
+ var canPlay = probe.canPlayType(mimeForProbe);
1055
+ var playable = isHls ? import_hls.default.isSupported() || canPlay !== "" : canPlay !== "";
1056
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1057
+ var details = {
1058
+ index: index,
1059
+ candidateUrl: file.url,
1060
+ candidateType: file.type,
1061
+ width: file.width,
1062
+ height: file.height,
1063
+ bitrate: file.bitrate,
1064
+ canPlayType: canPlay,
1065
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1066
+ };
1067
+ if (!playable) {
1068
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1069
+ reason: "rejected",
1070
+ why: "cannot_play_type"
1071
+ }));
1072
+ return;
1073
+ }
1074
+ var score = 0;
1075
+ if (target) {
1076
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1077
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1078
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1079
+ }
1080
+ accepted.push({
953
1081
  file: file,
954
1082
  score: score,
955
- resolutionDiff: resolutionDiff,
956
- bitrateDiff: bitrateDiff
957
- };
1083
+ insecure: insecure
1084
+ });
1085
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1086
+ reason: "accepted",
1087
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1088
+ score: score
1089
+ }));
958
1090
  });
959
- scoredFiles.sort(function(a, b) {
1091
+ accepted.sort(function(a, b) {
1092
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
960
1093
  return a.score - b.score;
961
1094
  });
962
- var bestMatch = scoredFiles[0];
963
- if (!bestMatch) {
964
- console.log("[HlsAdPlayer] No best match found, using first media file");
965
- return firstFile;
966
- }
967
- console.log("[HlsAdPlayer] Selected media file:", {
968
- url: bestMatch.file.url,
969
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
970
- bitrate: bestMatch.file.bitrate,
971
- score: bestMatch.score,
972
- resolutionDiff: bestMatch.resolutionDiff,
973
- bitrateDiff: bestMatch.bitrateDiff
1095
+ return accepted.map(function(entry) {
1096
+ return entry.file;
974
1097
  });
975
- return bestMatch.file;
976
1098
  }
977
1099
  function isHlsMediaFile(mediaFile) {
978
1100
  var type = mediaFile.type.toLowerCase();
@@ -989,59 +1111,181 @@ function createHlsAdPlayer(contentVideo, options) {
989
1111
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
990
1112
  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");
991
1113
  }
992
- function collectVideoMediaFiles(linear, verbose) {
1114
+ function getMediaProbe() {
1115
+ if (adVideoElement) return adVideoElement;
1116
+ if (!mediaProbe && typeof document !== "undefined") {
1117
+ mediaProbe = document.createElement("video");
1118
+ }
1119
+ return mediaProbe;
1120
+ }
1121
+ function evaluateMediaFile(mf) {
1122
+ var _mf_textContent;
1123
+ var type = mf.getAttribute("type") || "";
1124
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1125
+ var delivery = mf.getAttribute("delivery") || void 0;
1126
+ var codec = mf.getAttribute("codec") || void 0;
1127
+ if (!url) {
1128
+ return {
1129
+ category: "missing_media",
1130
+ whyRejected: "empty_url",
1131
+ canPlayType: ""
1132
+ };
1133
+ }
1134
+ var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1135
+ if (apiFramework === "VPAID") {
1136
+ return {
1137
+ category: "vpaid",
1138
+ whyRejected: "vpaid_not_supported",
1139
+ canPlayType: ""
1140
+ };
1141
+ }
1142
+ try {
1143
+ var protocol = new URL(url).protocol;
1144
+ if (protocol !== "https:" && protocol !== "http:") {
1145
+ return {
1146
+ category: "invalid_url",
1147
+ whyRejected: "protocol_".concat(protocol),
1148
+ canPlayType: ""
1149
+ };
1150
+ }
1151
+ } catch (unused) {
1152
+ return {
1153
+ category: "invalid_url",
1154
+ whyRejected: "unparseable_url",
1155
+ canPlayType: ""
1156
+ };
1157
+ }
1158
+ var bitrateAttr = mf.getAttribute("bitrate");
1159
+ var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1160
+ var file = {
1161
+ url: url,
1162
+ type: type,
1163
+ width: parseInt(mf.getAttribute("width") || "1920", 10),
1164
+ height: parseInt(mf.getAttribute("height") || "1080", 10),
1165
+ bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0,
1166
+ delivery: delivery,
1167
+ codec: codec
1168
+ };
1169
+ if (isAudioMediaFile(file)) {
1170
+ return {
1171
+ category: "audio_only",
1172
+ whyRejected: type.toLowerCase().startsWith("audio/") ? "audio_mime" : "audio_extension",
1173
+ canPlayType: ""
1174
+ };
1175
+ }
1176
+ var isHls = isHlsMediaFile(file);
1177
+ var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1178
+ if (!isHls && hasExplicitDimensions && (file.width <= 1 || file.height <= 1)) {
1179
+ return {
1180
+ category: "audio_only",
1181
+ whyRejected: "zero_dimensions",
1182
+ canPlayType: ""
1183
+ };
1184
+ }
1185
+ var probe = getMediaProbe();
1186
+ if (isHls) {
1187
+ var _ref;
1188
+ var nativeHls = (_ref = probe === null || probe === void 0 ? void 0 : probe.canPlayType("application/vnd.apple.mpegurl")) !== null && _ref !== void 0 ? _ref : "";
1189
+ if (import_hls.default.isSupported()) {
1190
+ return {
1191
+ file: file,
1192
+ whyAccepted: "hls_js",
1193
+ canPlayType: nativeHls
1194
+ };
1195
+ }
1196
+ if (nativeHls !== "") {
1197
+ return {
1198
+ file: file,
1199
+ whyAccepted: "native_hls",
1200
+ canPlayType: nativeHls
1201
+ };
1202
+ }
1203
+ return {
1204
+ category: "unsupported_hls",
1205
+ whyRejected: "no_hls_support",
1206
+ canPlayType: nativeHls
1207
+ };
1208
+ }
1209
+ if (!isProgressiveMediaFile(file)) {
1210
+ return {
1211
+ category: "unsupported_mime",
1212
+ whyRejected: "not_a_video_mime",
1213
+ canPlayType: ""
1214
+ };
1215
+ }
1216
+ if (!probe) {
1217
+ return {
1218
+ file: file,
1219
+ whyAccepted: "no_probe_available",
1220
+ canPlayType: ""
1221
+ };
1222
+ }
1223
+ var baseType = type || "video/mp4";
1224
+ var canPlay = probe.canPlayType(baseType);
1225
+ if (canPlay === "") {
1226
+ return {
1227
+ category: "unsupported_mime",
1228
+ whyRejected: "canPlayType_empty",
1229
+ canPlayType: canPlay
1230
+ };
1231
+ }
1232
+ if (codec) {
1233
+ var withCodec = probe.canPlayType("".concat(baseType, '; codecs="').concat(codec, '"'));
1234
+ if (withCodec === "") {
1235
+ return {
1236
+ category: "unsupported_codec",
1237
+ whyRejected: "codec_canPlayType_empty",
1238
+ canPlayType: withCodec
1239
+ };
1240
+ }
1241
+ return {
1242
+ file: file,
1243
+ whyAccepted: "canPlayType_".concat(withCodec),
1244
+ canPlayType: withCodec
1245
+ };
1246
+ }
1247
+ return {
1248
+ file: file,
1249
+ whyAccepted: "canPlayType_".concat(canPlay),
1250
+ canPlayType: canPlay
1251
+ };
1252
+ }
1253
+ function collectVideoMediaFiles(linear, verbose, stats) {
993
1254
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
994
1255
  var mediaFiles = [];
1256
+ if (stats) stats.total += mediaFileElements.length;
995
1257
  if (verbose) {
996
1258
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
997
1259
  }
998
1260
  mediaFileElements.forEach(function(mf, index) {
999
1261
  var _mf_textContent;
1000
- var type = mf.getAttribute("type") || "";
1262
+ var result = evaluateMediaFile(mf);
1001
1263
  var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1002
- var width = mf.getAttribute("width") || "";
1003
- var height = mf.getAttribute("height") || "";
1004
- if (verbose) {
1005
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ': type="').concat(type, '", url="').concat(url, '", width="').concat(width, '", height="').concat(height, '"'));
1006
- }
1007
- if (!url) {
1008
- if (verbose) {
1009
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, " has empty URL"));
1010
- }
1011
- return;
1012
- }
1013
- var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1014
- if (apiFramework === "VPAID") {
1015
- if (verbose) {
1016
- console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
1017
- }
1018
- return;
1019
- }
1020
- var bitrateAttr = mf.getAttribute("bitrate");
1021
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1022
- var mediaFile = {
1023
- url: url,
1024
- type: type,
1025
- width: parseInt(width || "1920", 10),
1026
- height: parseInt(height || "1080", 10),
1027
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
1028
- };
1029
- if (isAudioMediaFile(mediaFile)) {
1030
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1264
+ var accepted = "file" in result;
1265
+ logFunnel("mediafile_evaluated", {
1266
+ reason: accepted ? "accepted" : result.category,
1267
+ index: index,
1268
+ type: mf.getAttribute("type") || "",
1269
+ delivery: mf.getAttribute("delivery") || void 0,
1270
+ codec: mf.getAttribute("codec") || void 0,
1271
+ apiFramework: mf.getAttribute("apiFramework") || void 0,
1272
+ width: mf.getAttribute("width"),
1273
+ height: mf.getAttribute("height"),
1274
+ fileUrl: redactUrl(url),
1275
+ canPlayType: result.canPlayType,
1276
+ whyAccepted: accepted ? result.whyAccepted : void 0,
1277
+ whyRejected: accepted ? void 0 : result.whyRejected
1278
+ });
1279
+ if ("file" in result) {
1280
+ mediaFiles.push(result.file);
1031
1281
  return;
1032
1282
  }
1033
- var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1034
- if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1035
- 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'));
1036
- return;
1283
+ if (stats) {
1284
+ var _stats_categories_result_category;
1285
+ stats.categories[result.category] = ((_stats_categories_result_category = stats.categories[result.category]) !== null && _stats_categories_result_category !== void 0 ? _stats_categories_result_category : 0) + 1;
1037
1286
  }
1038
- if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {
1039
- mediaFiles.push(mediaFile);
1040
- if (verbose) {
1041
- console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1042
- }
1043
- } else if (verbose) {
1044
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1287
+ if (result.category === "audio_only") {
1288
+ console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (audio-only: ").concat(result.whyRejected, ', type="').concat(mf.getAttribute("type") || "", '") — audio-only ads are not played on video inventory'));
1045
1289
  }
1046
1290
  });
1047
1291
  return mediaFiles;
@@ -1165,26 +1409,58 @@ function createHlsAdPlayer(contentVideo, options) {
1165
1409
  }
1166
1410
  function parseVastXml(xmlString) {
1167
1411
  try {
1168
- var _adElements_find;
1169
1412
  var xmlDoc = parseXml(xmlString);
1170
1413
  if (!xmlDoc) return {
1171
1414
  type: "empty"
1172
1415
  };
1173
1416
  var root = xmlDoc.documentElement;
1174
1417
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1175
- var adElement = (_adElements_find = adElements.find(function(el) {
1176
- return getAdSequence(el) === void 0;
1177
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1178
- if (!adElement) {
1418
+ if (adElements.length === 0) {
1179
1419
  var _root_getAttribute;
1180
1420
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1181
1421
  return emptyVastResult(root);
1182
1422
  }
1183
- var parsed = parseAdElement(adElement, true);
1184
- if (parsed.type === "wrapper") {
1185
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1423
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1424
+ return getAdSequence(el) === void 0;
1425
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1426
+ return getAdSequence(el) !== void 0;
1427
+ })));
1428
+ var firstEmpty;
1429
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1430
+ try {
1431
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1432
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1433
+ var parsed = parseAdElement(adElement, true);
1434
+ if (parsed.type === "empty") {
1435
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1436
+ continue;
1437
+ }
1438
+ if (index > 0) {
1439
+ logFunnel("vast_ad_fallback", {
1440
+ usedAdIndex: index,
1441
+ adCount: ordered.length
1442
+ });
1443
+ }
1444
+ if (parsed.type === "wrapper") {
1445
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1446
+ }
1447
+ return parsed;
1448
+ }
1449
+ } catch (err) {
1450
+ _didIteratorError = true;
1451
+ _iteratorError = err;
1452
+ } finally{
1453
+ try {
1454
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1455
+ _iterator.return();
1456
+ }
1457
+ } finally{
1458
+ if (_didIteratorError) {
1459
+ throw _iteratorError;
1460
+ }
1461
+ }
1186
1462
  }
1187
- return parsed;
1463
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1188
1464
  } catch (error) {
1189
1465
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1190
1466
  return {
@@ -1230,6 +1506,10 @@ function createHlsAdPlayer(contentVideo, options) {
1230
1506
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1231
1507
  if (adElement.getAttribute("conditionalAd") === "true") {
1232
1508
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1509
+ logFunnel("vast_no_supported_media", {
1510
+ reason: "vpaid",
1511
+ conditionalAd: true
1512
+ });
1233
1513
  return {
1234
1514
  type: "empty",
1235
1515
  errorUrls: errorUrls,
@@ -1238,11 +1518,15 @@ function createHlsAdPlayer(contentVideo, options) {
1238
1518
  }
1239
1519
  var linear;
1240
1520
  var mediaFiles = [];
1521
+ var rejectStats = {
1522
+ total: 0,
1523
+ categories: {}
1524
+ };
1241
1525
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1242
1526
  try {
1243
1527
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1244
1528
  var candidate = _step.value;
1245
- var files = collectVideoMediaFiles(candidate, verbose);
1529
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1246
1530
  if (files.length > 0) {
1247
1531
  linear = candidate;
1248
1532
  mediaFiles = files;
@@ -1265,6 +1549,39 @@ function createHlsAdPlayer(contentVideo, options) {
1265
1549
  }
1266
1550
  if (!linear) {
1267
1551
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1552
+ var reason = "missing_media";
1553
+ var top = 0;
1554
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1555
+ try {
1556
+ for(var _iterator1 = Object.keys(rejectStats.categories)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1557
+ var category = _step1.value;
1558
+ var _rejectStats_categories_category;
1559
+ var count = (_rejectStats_categories_category = rejectStats.categories[category]) !== null && _rejectStats_categories_category !== void 0 ? _rejectStats_categories_category : 0;
1560
+ if (count > top) {
1561
+ top = count;
1562
+ reason = category;
1563
+ }
1564
+ }
1565
+ } catch (err) {
1566
+ _didIteratorError1 = true;
1567
+ _iteratorError1 = err;
1568
+ } finally{
1569
+ try {
1570
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1571
+ _iterator1.return();
1572
+ }
1573
+ } finally{
1574
+ if (_didIteratorError1) {
1575
+ throw _iteratorError1;
1576
+ }
1577
+ }
1578
+ }
1579
+ if (rejectStats.total > 0 && top === 0) reason = "other";
1580
+ logFunnel("vast_no_supported_media", {
1581
+ reason: reason,
1582
+ mediaFileCount: rejectStats.total,
1583
+ rejectedByCategory: rejectStats.categories
1584
+ });
1268
1585
  return {
1269
1586
  type: "empty",
1270
1587
  errorUrls: errorUrls,
@@ -1294,27 +1611,65 @@ function createHlsAdPlayer(contentVideo, options) {
1294
1611
  }
1295
1612
  }
1296
1613
  function fetchVastXml(vastTagUrl) {
1297
- var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include";
1614
+ var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include", kind = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "gam";
1298
1615
  return _async_to_generator(function() {
1299
- var controller, timeoutId, requestVast, response, error, error1;
1616
+ var controller, timeoutId, startedAt, attempt, requestVast, response, error, error1;
1300
1617
  return _ts_generator(this, function(_state) {
1301
1618
  switch(_state.label){
1302
1619
  case 0:
1620
+ if (destroyed) {
1621
+ throw new Error("VAST request skipped: ad player destroyed");
1622
+ }
1303
1623
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1624
+ if (controller) pendingVastRequests.add(controller);
1304
1625
  timeoutId = controller ? setTimeout(function() {
1305
1626
  return controller.abort();
1306
1627
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
1628
+ startedAt = Date.now();
1629
+ attempt = 0;
1307
1630
  requestVast = function requestVast(creds) {
1308
- return fetch(vastTagUrl, _object_spread({
1309
- mode: "cors",
1310
- credentials: creds,
1311
- headers: {
1312
- "Accept": "application/xml, text/xml, */*"
1313
- },
1314
- referrerPolicy: "no-referrer-when-downgrade"
1315
- }, controller ? {
1316
- signal: controller.signal
1317
- } : {}));
1631
+ return _async_to_generator(function() {
1632
+ var response;
1633
+ return _ts_generator(this, function(_state) {
1634
+ switch(_state.label){
1635
+ case 0:
1636
+ attempt++;
1637
+ if (kind === "gam") {
1638
+ logFunnel("gam_http_request_sent", {
1639
+ attempt: attempt,
1640
+ credentials: creds
1641
+ });
1642
+ }
1643
+ return [
1644
+ 4,
1645
+ fetch(vastTagUrl, _object_spread({
1646
+ mode: "cors",
1647
+ credentials: creds,
1648
+ headers: {
1649
+ "Accept": "application/xml, text/xml, */*"
1650
+ },
1651
+ referrerPolicy: "no-referrer-when-downgrade"
1652
+ }, controller ? {
1653
+ signal: controller.signal
1654
+ } : {}))
1655
+ ];
1656
+ case 1:
1657
+ response = _state.sent();
1658
+ if (kind === "gam") {
1659
+ logFunnel("gam_response_received", {
1660
+ attempt: attempt,
1661
+ httpStatus: response.status,
1662
+ ok: response.ok,
1663
+ elapsedMs: Date.now() - startedAt
1664
+ });
1665
+ }
1666
+ return [
1667
+ 2,
1668
+ response
1669
+ ];
1670
+ }
1671
+ });
1672
+ })();
1318
1673
  };
1319
1674
  _state.label = 1;
1320
1675
  case 1:
@@ -1349,6 +1704,9 @@ function createHlsAdPlayer(contentVideo, options) {
1349
1704
  6
1350
1705
  ];
1351
1706
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1707
+ logFunnel("vast_credentials_retry", {
1708
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1709
+ });
1352
1710
  return [
1353
1711
  4,
1354
1712
  requestVast("omit")
@@ -1368,7 +1726,7 @@ function createHlsAdPlayer(contentVideo, options) {
1368
1726
  ];
1369
1727
  case 8:
1370
1728
  if (!response.ok) {
1371
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
1729
+ throw new Error("Failed to fetch VAST: HTTP ".concat(response.status, " ").concat(response.statusText));
1372
1730
  }
1373
1731
  return [
1374
1732
  4,
@@ -1382,11 +1740,15 @@ function createHlsAdPlayer(contentVideo, options) {
1382
1740
  case 10:
1383
1741
  error1 = _state.sent();
1384
1742
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1743
+ if (pendingRequestAbortReason) {
1744
+ throw new Error("".concat(pendingRequestAbortReason, ": ").concat(vastTagUrl));
1745
+ }
1385
1746
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1386
1747
  }
1387
1748
  throw error1;
1388
1749
  case 11:
1389
1750
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1751
+ if (controller) pendingVastRequests.delete(controller);
1390
1752
  return [
1391
1753
  7
1392
1754
  ];
@@ -1400,7 +1762,7 @@ function createHlsAdPlayer(contentVideo, options) {
1400
1762
  }
1401
1763
  function fetchAndParseVastAd(_0) {
1402
1764
  return _async_to_generator(function(vastTagUrl) {
1403
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1765
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1404
1766
  var _arguments = arguments;
1405
1767
  return _ts_generator(this, function(_state) {
1406
1768
  switch(_state.label){
@@ -1408,6 +1770,11 @@ function createHlsAdPlayer(contentVideo, options) {
1408
1770
  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] : {
1409
1771
  followAdditionalWrappers: true
1410
1772
  };
1773
+ if (destroyed) return [
1774
+ 2,
1775
+ null
1776
+ ];
1777
+ fetchStartedAt = Date.now();
1411
1778
  _state.label = 1;
1412
1779
  case 1:
1413
1780
  _state.trys.push([
@@ -1418,7 +1785,7 @@ function createHlsAdPlayer(contentVideo, options) {
1418
1785
  ]);
1419
1786
  return [
1420
1787
  4,
1421
- fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit")
1788
+ fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit", depth === 0 ? "gam" : "wrapper")
1422
1789
  ];
1423
1790
  case 2:
1424
1791
  vastXml = _state.sent();
@@ -1430,14 +1797,35 @@ function createHlsAdPlayer(contentVideo, options) {
1430
1797
  error = _state.sent();
1431
1798
  if (depth === 0) throw error;
1432
1799
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1433
- fireTrackingPixels(accumulatedTracking.error, {
1434
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1800
+ logFunnel("wrapper_fetch", {
1801
+ reason: "failure",
1802
+ depth: depth,
1803
+ wrapperUrl: redactUrl(vastTagUrl),
1804
+ elapsedMs: Date.now() - fetchStartedAt,
1805
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1435
1806
  });
1807
+ if (!destroyed) {
1808
+ fireTrackingPixels(accumulatedTracking.error, {
1809
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1810
+ });
1811
+ }
1436
1812
  return [
1437
1813
  2,
1438
1814
  null
1439
1815
  ];
1440
1816
  case 4:
1817
+ if (destroyed) return [
1818
+ 2,
1819
+ null
1820
+ ];
1821
+ if (depth > 0) {
1822
+ logFunnel("wrapper_fetch", {
1823
+ reason: "success",
1824
+ depth: depth,
1825
+ wrapperUrl: redactUrl(vastTagUrl),
1826
+ elapsedMs: Date.now() - fetchStartedAt
1827
+ });
1828
+ }
1441
1829
  console.log("[HlsAdPlayer] VAST XML received");
1442
1830
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1443
1831
  parsed = parseVastXml(vastXml);
@@ -1469,6 +1857,9 @@ function createHlsAdPlayer(contentVideo, options) {
1469
1857
  ];
1470
1858
  }
1471
1859
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1860
+ logFunnel("inline_resolved", {
1861
+ depth: depth
1862
+ });
1472
1863
  return [
1473
1864
  2,
1474
1865
  parsed.ad
@@ -1479,20 +1870,29 @@ function createHlsAdPlayer(contentVideo, options) {
1479
1870
  }
1480
1871
  function fetchAndParsePod(vastTagUrl) {
1481
1872
  return _async_to_generator(function() {
1482
- 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;
1873
+ var _root_getAttribute, _root_getAttribute1, vastXml, trimmedXml, xmlDoc, root, adElements, _root_getAttribute2, _empty_errorUrls, empty, _empty_errorCode, resolveAd, podElements, buffet, resolveAll, ads, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, ad, err, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, ad1, err;
1483
1874
  return _ts_generator(this, function(_state) {
1484
1875
  switch(_state.label){
1485
1876
  case 0:
1877
+ lastPodAdElementCount = 0;
1486
1878
  return [
1487
1879
  4,
1488
1880
  fetchVastXml(vastTagUrl)
1489
1881
  ];
1490
1882
  case 1:
1491
1883
  vastXml = _state.sent();
1884
+ if (destroyed) return [
1885
+ 2,
1886
+ []
1887
+ ];
1492
1888
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1493
1889
  trimmedXml = vastXml.trim();
1494
1890
  if (trimmedXml.length === 0) {
1495
1891
  console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)");
1892
+ logFunnel("vast_parsed", {
1893
+ adElementCount: 0,
1894
+ reason: "empty_body"
1895
+ });
1496
1896
  return [
1497
1897
  2,
1498
1898
  []
@@ -1501,6 +1901,10 @@ function createHlsAdPlayer(contentVideo, options) {
1501
1901
  xmlDoc = parseXml(vastXml);
1502
1902
  if (!xmlDoc) {
1503
1903
  console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1904
+ logFunnel("vast_parsed", {
1905
+ adElementCount: 0,
1906
+ reason: "xml_parse_error"
1907
+ });
1504
1908
  return [
1505
1909
  2,
1506
1910
  []
@@ -1508,10 +1912,21 @@ function createHlsAdPlayer(contentVideo, options) {
1508
1912
  }
1509
1913
  root = xmlDoc.documentElement;
1510
1914
  adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1915
+ logFunnel("vast_parsed", {
1916
+ reason: adElements.length > 0 ? "has_ads" : "no_ads",
1917
+ vastVersion: (_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : void 0,
1918
+ adElementCount: adElements.length,
1919
+ inlineCount: adElements.filter(function(el) {
1920
+ return el.querySelector(":scope > InLine");
1921
+ }).length,
1922
+ wrapperCount: adElements.filter(function(el) {
1923
+ return el.querySelector(":scope > Wrapper");
1924
+ }).length
1925
+ });
1511
1926
  if (adElements.length === 0) {
1512
1927
  ;
1513
1928
  ;
1514
- console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat((_root_getAttribute1 = root.getAttribute("version")) !== null && _root_getAttribute1 !== void 0 ? _root_getAttribute1 : "", " pod response (no fill)"));
1929
+ console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat((_root_getAttribute2 = root.getAttribute("version")) !== null && _root_getAttribute2 !== void 0 ? _root_getAttribute2 : "", " pod response (no fill)"));
1515
1930
  empty = emptyVastResult(root);
1516
1931
  if (empty.type === "empty" && ((_empty_errorUrls = empty.errorUrls) === null || _empty_errorUrls === void 0 ? void 0 : _empty_errorUrls.length)) {
1517
1932
  ;
@@ -1529,10 +1944,15 @@ function createHlsAdPlayer(contentVideo, options) {
1529
1944
  var _parsed_errorUrls, parsed, _parsed_errorCode;
1530
1945
  return _ts_generator(this, function(_state) {
1531
1946
  parsed = parseAdElement(adElement);
1532
- if (parsed.type === "inline") return [
1533
- 2,
1534
- parsed.ad
1535
- ];
1947
+ if (parsed.type === "inline") {
1948
+ logFunnel("inline_resolved", {
1949
+ depth: 0
1950
+ });
1951
+ return [
1952
+ 2,
1953
+ parsed.ad
1954
+ ];
1955
+ }
1536
1956
  if (parsed.type === "wrapper") {
1537
1957
  return [
1538
1958
  2,
@@ -1710,7 +2130,8 @@ function createHlsAdPlayer(contentVideo, options) {
1710
2130
  7
1711
2131
  ];
1712
2132
  case 21:
1713
- console.log("[HlsAdPlayer] Parsed ".concat(ads.length, " ad(s) from VAST ").concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " pod response"));
2133
+ console.log("[HlsAdPlayer] Parsed ".concat(ads.length, " ad(s) from VAST ").concat((_root_getAttribute1 = root.getAttribute("version")) !== null && _root_getAttribute1 !== void 0 ? _root_getAttribute1 : "", " pod response"));
2134
+ lastPodAdElementCount = adElements.length;
1714
2135
  return [
1715
2136
  2,
1716
2137
  ads
@@ -1776,14 +2197,17 @@ function createHlsAdPlayer(contentVideo, options) {
1776
2197
  var progress = currentTime / currentAd.duration;
1777
2198
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1778
2199
  trackingFired.firstQuartile = true;
2200
+ logFunnel("first_quartile");
1779
2201
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1780
2202
  }
1781
2203
  if (progress >= 0.5 && !trackingFired.midpoint) {
1782
2204
  trackingFired.midpoint = true;
2205
+ logFunnel("midpoint");
1783
2206
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1784
2207
  }
1785
2208
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1786
2209
  trackingFired.thirdQuartile = true;
2210
+ logFunnel("third_quartile");
1787
2211
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1788
2212
  }
1789
2213
  };
@@ -1806,6 +2230,16 @@ function createHlsAdPlayer(contentVideo, options) {
1806
2230
  if (!trackingFired.impression) {
1807
2231
  trackingFired.impression = true;
1808
2232
  resolvedAds.add(currentAd);
2233
+ logFunnel("playing", {
2234
+ mutedByAutoplay: forcedMuteByAutoplay,
2235
+ candidateIndex: mediaCandidateIndex
2236
+ });
2237
+ logFunnel("impression_fired", {
2238
+ pixelCount: currentAd.trackingUrls.impression.length
2239
+ });
2240
+ if (currentAd.trackingUrls.impression.length === 0) {
2241
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2242
+ }
1809
2243
  fireTrackingPixels(currentAd.trackingUrls.impression);
1810
2244
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1811
2245
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1828,6 +2262,7 @@ function createHlsAdPlayer(contentVideo, options) {
1828
2262
  sampleViewability();
1829
2263
  settleViewability();
1830
2264
  trackingFired.complete = true;
2265
+ logFunnel("complete");
1831
2266
  fireTrackingPixels(currentAd.trackingUrls.complete);
1832
2267
  console.log("[HlsAdPlayer] Ad completed");
1833
2268
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1836,16 +2271,41 @@ function createHlsAdPlayer(contentVideo, options) {
1836
2271
  handleAdComplete();
1837
2272
  };
1838
2273
  var onError = function onError(e) {
2274
+ var _adVideoElement_error, _adVideoElement_error1;
1839
2275
  if (!adPlaying) return;
1840
2276
  console.error("[HlsAdPlayer] Ad video error:", e);
1841
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1842
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1843
- return;
1844
- }
1845
- handleAdError();
2277
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2278
+ logFunnel("media_error", {
2279
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2280
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2281
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2282
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2283
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2284
+ vastErrorCode: vastErrorCode
2285
+ });
2286
+ recoverFromAdFailure(vastErrorCode);
2287
+ };
2288
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2289
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2290
+ if (!adVideoElement.currentSrc) return;
2291
+ logFunnel("media_event", {
2292
+ reason: event.type,
2293
+ readyState: adVideoElement.readyState,
2294
+ networkState: adVideoElement.networkState,
2295
+ currentSrc: adVideoElement.currentSrc
2296
+ });
1846
2297
  };
1847
2298
  var onVolumeChange = function onVolumeChange() {
1848
2299
  if (!currentAd || !adVideoElement) return;
2300
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2301
+ var userActivation = navigator.userActivation;
2302
+ if (userActivation && !userActivation.isActive) {
2303
+ logFunnel("unexpected_unmute", {
2304
+ paused: adVideoElement.paused
2305
+ });
2306
+ }
2307
+ forcedMuteByAutoplay = false;
2308
+ }
1849
2309
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1850
2310
  if (!trackingFired.start) {
1851
2311
  trackingFired.lastMuted = muted;
@@ -1905,6 +2365,22 @@ function createHlsAdPlayer(contentVideo, options) {
1905
2365
  {
1906
2366
  type: "play",
1907
2367
  handler: onPlay
2368
+ },
2369
+ {
2370
+ type: "stalled",
2371
+ handler: onMediaDiagnostic
2372
+ },
2373
+ {
2374
+ type: "suspend",
2375
+ handler: onMediaDiagnostic
2376
+ },
2377
+ {
2378
+ type: "abort",
2379
+ handler: onMediaDiagnostic
2380
+ },
2381
+ {
2382
+ type: "emptied",
2383
+ handler: onMediaDiagnostic
1908
2384
  }
1909
2385
  ];
1910
2386
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2194,16 +2670,51 @@ function createHlsAdPlayer(contentVideo, options) {
2194
2670
  function settlePendingPlay() {
2195
2671
  pendingPlayPromise = void 0;
2196
2672
  }
2673
+ function toVastPlayErrorCode(error) {
2674
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2675
+ }
2676
+ function failAdPlayback(context, error) {
2677
+ var vastErrorCode = toVastPlayErrorCode(error);
2678
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2679
+ logFunnel("play_failed", {
2680
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2681
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2682
+ vastErrorCode: vastErrorCode
2683
+ });
2684
+ recoverFromAdFailure(vastErrorCode);
2685
+ }
2197
2686
  function startAdPlayback(context) {
2687
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2198
2688
  if (!adVideoElement) return;
2689
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2690
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2691
+ context: context,
2692
+ isConnected: adVideoElement.isConnected,
2693
+ clientWidth: adVideoElement.clientWidth,
2694
+ clientHeight: adVideoElement.clientHeight,
2695
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2696
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2697
+ });
2199
2698
  var playPromise = adVideoElement.play();
2200
2699
  pendingPlayPromise = playPromise;
2201
2700
  playPromise.catch(function(error) {
2202
2701
  if (pendingPlayPromise !== playPromise) {
2203
2702
  return;
2204
2703
  }
2205
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2206
- handleAdError();
2704
+ logFunnel("play_rejected", {
2705
+ context: context,
2706
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2707
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2708
+ });
2709
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2710
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2711
+ originalMutedState = true;
2712
+ forcedMuteByAutoplay = true;
2713
+ adVideoElement.muted = true;
2714
+ startAdPlayback(context, true);
2715
+ return;
2716
+ }
2717
+ failAdPlayback(context, error);
2207
2718
  }).finally(function() {
2208
2719
  if (pendingPlayPromise === playPromise) {
2209
2720
  pendingPlayPromise = void 0;
@@ -2242,17 +2753,109 @@ function createHlsAdPlayer(contentVideo, options) {
2242
2753
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2243
2754
  adVideoElement.muted = originalMutedState;
2244
2755
  }
2756
+ function clearMediaStartTimer() {
2757
+ if (mediaStartTimerId !== void 0) {
2758
+ clearTimeout(mediaStartTimerId);
2759
+ mediaStartTimerId = void 0;
2760
+ }
2761
+ }
2762
+ function startMediaStartTimer() {
2763
+ clearMediaStartTimer();
2764
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2765
+ var startedAt = Date.now();
2766
+ mediaStartTimerId = setTimeout(function() {
2767
+ mediaStartTimerId = void 0;
2768
+ if (!adPlaying || trackingFired.impression) return;
2769
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2770
+ logFunnel("play_resolved_but_never_started", {
2771
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2772
+ elapsedMs: Date.now() - startedAt,
2773
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2774
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2775
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2776
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2777
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2778
+ });
2779
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2780
+ }, MEDIA_START_TIMEOUT_MS);
2781
+ }
2782
+ function resetVideoElementForNextSource() {
2783
+ clearStallWatchdog();
2784
+ if (requiresMediaPipelineResetAfterAds()) {
2785
+ recreateAdVideoElement();
2786
+ setupAdEventListeners();
2787
+ } else {
2788
+ prepareVideoElementForNewSource();
2789
+ }
2790
+ }
2791
+ function tryNextMediaCandidate() {
2792
+ if (!currentAd || trackingFired.impression) return false;
2793
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2794
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2795
+ mediaCandidateIndex++;
2796
+ var next = mediaCandidates[mediaCandidateIndex];
2797
+ if (!next) return false;
2798
+ logFunnel("media_fallback", {
2799
+ failedUrl: failedUrl,
2800
+ nextUrl: next.url,
2801
+ nextType: next.type,
2802
+ candidateIndex: mediaCandidateIndex,
2803
+ candidateCount: mediaCandidates.length
2804
+ });
2805
+ resetVideoElementForNextSource();
2806
+ try {
2807
+ loadMediaCandidate(next);
2808
+ return true;
2809
+ } catch (error) {
2810
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2811
+ return tryNextMediaCandidate();
2812
+ }
2813
+ }
2814
+ function recoverFromAdFailure(vastErrorCode) {
2815
+ clearMediaStartTimer();
2816
+ if (tryNextMediaCandidate()) return;
2817
+ reportCurrentAdError(vastErrorCode);
2818
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2819
+ handleAdError();
2820
+ }
2245
2821
  function loadCurrentAdMedia() {
2246
2822
  if (!adVideoElement || !currentAd) {
2247
2823
  throw new Error("No ad video element or ad to load");
2248
2824
  }
2249
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2825
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2826
+ mediaCandidateIndex = 0;
2827
+ var mediaFile = mediaCandidates[0];
2250
2828
  if (!mediaFile) {
2251
- throw new Error("No media file available for ad");
2829
+ logFunnel("media_unsupported", {
2830
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2831
+ candidates: currentAd.mediaFiles.length
2832
+ });
2833
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2834
+ throw new Error("No media file this browser can play");
2835
+ }
2836
+ try {
2837
+ loadMediaCandidate(mediaFile);
2838
+ } catch (error) {
2839
+ if (tryNextMediaCandidate()) return;
2840
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2841
+ throw error;
2842
+ }
2843
+ }
2844
+ function loadMediaCandidate(mediaFile) {
2845
+ if (!adVideoElement || !currentAd) {
2846
+ throw new Error("No ad video element or ad to load");
2252
2847
  }
2253
2848
  currentAdMediaFile = mediaFile;
2254
2849
  var isHlsAd = isHlsMediaFile(mediaFile);
2850
+ logFunnel("media_selected", {
2851
+ width: mediaFile.width,
2852
+ height: mediaFile.height,
2853
+ bitrate: mediaFile.bitrate,
2854
+ candidateIndex: mediaCandidateIndex,
2855
+ candidates: mediaCandidates.length
2856
+ });
2255
2857
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2858
+ startMediaStartTimer();
2256
2859
  if (isHlsAd && import_hls.default.isSupported()) {
2257
2860
  if (adHls) {
2258
2861
  adHls.destroy();
@@ -2261,6 +2864,9 @@ function createHlsAdPlayer(contentVideo, options) {
2261
2864
  enableWorker: true,
2262
2865
  lowLatencyMode: false
2263
2866
  });
2867
+ logFunnel("media_load", {
2868
+ pipeline: "hls.js"
2869
+ });
2264
2870
  adHls.loadSource(mediaFile.url);
2265
2871
  adHls.attachMedia(adVideoElement);
2266
2872
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2270,10 +2876,24 @@ function createHlsAdPlayer(contentVideo, options) {
2270
2876
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2271
2877
  console.error("[HlsAdPlayer] HLS error:", data);
2272
2878
  if (data.fatal) {
2273
- handleAdError();
2879
+ var _data_response, _data_response1, _data_frag;
2880
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2881
+ logFunnel("hls_fatal", {
2882
+ reason: data.details,
2883
+ errorName: data.type,
2884
+ errorMessage: data.details,
2885
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2886
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2887
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2888
+ vastErrorCode: vastErrorCode
2889
+ });
2890
+ recoverFromAdFailure(vastErrorCode);
2274
2891
  }
2275
2892
  });
2276
2893
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2894
+ logFunnel("media_load", {
2895
+ pipeline: "native-hls"
2896
+ });
2277
2897
  adVideoElement.src = mediaFile.url;
2278
2898
  startAdPlayback("native HLS ad playback");
2279
2899
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2281,45 +2901,47 @@ function createHlsAdPlayer(contentVideo, options) {
2281
2901
  adHls.destroy();
2282
2902
  adHls = void 0;
2283
2903
  }
2904
+ logFunnel("media_load", {
2905
+ pipeline: "progressive"
2906
+ });
2284
2907
  adVideoElement.src = mediaFile.url;
2285
2908
  adVideoElement.load();
2286
2909
  startAdPlayback("progressive ad playback");
2287
2910
  } else {
2911
+ clearMediaStartTimer();
2912
+ logFunnel("media_unsupported", {
2913
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2914
+ });
2288
2915
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2289
2916
  }
2290
2917
  }
2291
2918
  function advanceToNextPodAd() {
2292
- if (podIndex >= podAds.length - 1) {
2293
- return false;
2294
- }
2295
- settleViewability();
2296
- podIndex++;
2297
- currentAd = podAds[podIndex];
2298
- currentAdMediaFile = void 0;
2299
- resetAdTracking();
2300
- if (currentAd) {
2301
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2302
- }
2303
- clearStallWatchdog();
2304
- if (requiresMediaPipelineResetAfterAds()) {
2305
- recreateAdVideoElement();
2306
- setupAdEventListeners();
2307
- } else {
2308
- prepareVideoElementForNewSource();
2309
- }
2310
- try {
2311
- loadCurrentAdMedia();
2312
- emit("pod_ad_started", {
2313
- index: podIndex,
2314
- total: podAds.length
2315
- });
2316
- return true;
2317
- } catch (error) {
2318
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2319
- return false;
2919
+ clearMediaStartTimer();
2920
+ while(podIndex < podAds.length - 1){
2921
+ settleViewability();
2922
+ podIndex++;
2923
+ currentAd = podAds[podIndex];
2924
+ currentAdMediaFile = void 0;
2925
+ resetAdTracking();
2926
+ if (currentAd) {
2927
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2928
+ }
2929
+ resetVideoElementForNextSource();
2930
+ try {
2931
+ loadCurrentAdMedia();
2932
+ emit("pod_ad_started", {
2933
+ index: podIndex,
2934
+ total: podAds.length
2935
+ });
2936
+ return true;
2937
+ } catch (error) {
2938
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2939
+ }
2320
2940
  }
2941
+ return false;
2321
2942
  }
2322
2943
  function clearStallWatchdog() {
2944
+ clearMediaStartTimer();
2323
2945
  if (stallWatchdogId != null) {
2324
2946
  clearInterval(stallWatchdogId);
2325
2947
  stallWatchdogId = void 0;
@@ -2335,11 +2957,10 @@ function createHlsAdPlayer(contentVideo, options) {
2335
2957
  function handleAdStall() {
2336
2958
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2337
2959
  clearStallWatchdog();
2338
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2339
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2340
- return;
2341
- }
2342
- handleAdError();
2960
+ logFunnel("stall", {
2961
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2962
+ });
2963
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2343
2964
  }
2344
2965
  function getDecodedVideoFrameCount(video) {
2345
2966
  try {
@@ -2401,11 +3022,10 @@ function createHlsAdPlayer(contentVideo, options) {
2401
3022
  function handleVideoDecodeFailure() {
2402
3023
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2403
3024
  clearStallWatchdog();
2404
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2405
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2406
- return;
2407
- }
2408
- handleAdError();
3025
+ logFunnel("decode_failure", {
3026
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
3027
+ });
3028
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2409
3029
  }
2410
3030
  function startStallWatchdog() {
2411
3031
  clearStallWatchdog();
@@ -2529,6 +3149,15 @@ function createHlsAdPlayer(contentVideo, options) {
2529
3149
  Promise.reject(new Error("Ad already playing"))
2530
3150
  ];
2531
3151
  }
3152
+ if (destroyed) {
3153
+ return [
3154
+ 2,
3155
+ Promise.reject(new Error("Ad player destroyed"))
3156
+ ];
3157
+ }
3158
+ currentVastTagUrl = vastTagUrl;
3159
+ pendingRequestAbortReason = void 0;
3160
+ logFunnel("request_sent");
2532
3161
  _state.label = 1;
2533
3162
  case 1:
2534
3163
  _state.trys.push([
@@ -2563,8 +3192,29 @@ function createHlsAdPlayer(contentVideo, options) {
2563
3192
  ads = _state.sent();
2564
3193
  _state.label = 4;
2565
3194
  case 4:
3195
+ if (destroyed) {
3196
+ return [
3197
+ 2,
3198
+ Promise.reject(new Error("Ad player destroyed"))
3199
+ ];
3200
+ }
3201
+ if (!ads.length && pendingRequestAbortReason) {
3202
+ throw new Error(pendingRequestAbortReason);
3203
+ }
3204
+ if (!ads.length && lastPodAdElementCount > 0) {
3205
+ console.warn("[HlsAdPlayer] VAST response had ads but none were playable");
3206
+ logFunnel("vast_fill_rejected", {
3207
+ adElementCount: lastPodAdElementCount
3208
+ });
3209
+ emit("ad_error");
3210
+ return [
3211
+ 2,
3212
+ Promise.reject(new Error("VAST fill rejected: no playable ad in response"))
3213
+ ];
3214
+ }
2566
3215
  if (!ads.length) {
2567
3216
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3217
+ logFunnel("no_fill");
2568
3218
  emit("ad_error");
2569
3219
  return [
2570
3220
  2,
@@ -2575,6 +3225,23 @@ function createHlsAdPlayer(contentVideo, options) {
2575
3225
  podIndex = 0;
2576
3226
  currentAd = ads[0];
2577
3227
  currentAdMediaFile = void 0;
3228
+ logFunnel("vast_received", {
3229
+ adCount: ads.length,
3230
+ durations: ads.map(function(ad) {
3231
+ return ad.duration;
3232
+ }),
3233
+ impressionUrls: ads.map(function(ad) {
3234
+ return ad.trackingUrls.impression.length;
3235
+ })
3236
+ });
3237
+ ads.forEach(function(ad, index) {
3238
+ if (ad.trackingUrls.impression.length === 0) {
3239
+ logFunnel("vast_missing_impression", {
3240
+ adIndex: index,
3241
+ missingAdId: ad.id
3242
+ });
3243
+ }
3244
+ });
2578
3245
  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"));
2579
3246
  return [
2580
3247
  2,
@@ -2583,6 +3250,9 @@ function createHlsAdPlayer(contentVideo, options) {
2583
3250
  case 5:
2584
3251
  error = _state.sent();
2585
3252
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3253
+ logFunnel("request_failed", {
3254
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3255
+ });
2586
3256
  emit("ad_error");
2587
3257
  return [
2588
3258
  2,
@@ -2638,13 +3308,22 @@ function createHlsAdPlayer(contentVideo, options) {
2638
3308
  adContainerEl.style.pointerEvents = "auto";
2639
3309
  }
2640
3310
  emit("content_pause");
2641
- loadCurrentAdMedia();
3311
+ try {
3312
+ loadCurrentAdMedia();
3313
+ } catch (loadError) {
3314
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3315
+ throw loadError;
3316
+ }
3317
+ }
2642
3318
  return [
2643
3319
  2,
2644
3320
  Promise.resolve()
2645
3321
  ];
2646
3322
  } catch (error) {
2647
3323
  console.error("[HlsAdPlayer] Error playing ad:", error);
3324
+ logFunnel("play_failed", {
3325
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3326
+ });
2648
3327
  handleAdError();
2649
3328
  return [
2650
3329
  2,
@@ -2686,6 +3365,9 @@ function createHlsAdPlayer(contentVideo, options) {
2686
3365
  var previousMutedState;
2687
3366
  return _ts_generator(this, function(_state) {
2688
3367
  console.log("[HlsAdPlayer] Stopping ad");
3368
+ if (adPlaying && currentAd && !trackingFired.impression) {
3369
+ logFunnel("stopped_before_start");
3370
+ }
2689
3371
  settleViewability();
2690
3372
  fireNotUsedForUnplayedAds();
2691
3373
  clearStallWatchdog();
@@ -2718,15 +3400,18 @@ function createHlsAdPlayer(contentVideo, options) {
2718
3400
  },
2719
3401
  destroy: function destroy() {
2720
3402
  console.log("[HlsAdPlayer] Destroying");
3403
+ if (adPlaying && currentAd && !trackingFired.impression) {
3404
+ logFunnel("stopped_before_start");
3405
+ }
2721
3406
  settleViewability();
2722
3407
  fireNotUsedForUnplayedAds();
2723
3408
  destroyed = true;
2724
- clearStallWatchdog();
3409
+ pendingRequestAbortReason = "Ad player destroyed";
2725
3410
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2726
3411
  try {
2727
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2728
- var timeoutId = _step.value;
2729
- clearTimeout(timeoutId);
3412
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3413
+ var controller = _step.value;
3414
+ controller.abort();
2730
3415
  }
2731
3416
  } catch (err) {
2732
3417
  _didIteratorError = true;
@@ -2742,6 +3427,28 @@ function createHlsAdPlayer(contentVideo, options) {
2742
3427
  }
2743
3428
  }
2744
3429
  }
3430
+ pendingVastRequests.clear();
3431
+ clearStallWatchdog();
3432
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3433
+ try {
3434
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3435
+ var timeoutId = _step1.value;
3436
+ clearTimeout(timeoutId);
3437
+ }
3438
+ } catch (err) {
3439
+ _didIteratorError1 = true;
3440
+ _iteratorError1 = err;
3441
+ } finally{
3442
+ try {
3443
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3444
+ _iterator1.return();
3445
+ }
3446
+ } finally{
3447
+ if (_didIteratorError1) {
3448
+ throw _iteratorError1;
3449
+ }
3450
+ }
3451
+ }
2745
3452
  pendingTimeouts = [];
2746
3453
  adPlaying = false;
2747
3454
  setAdPlayingFlag(false);
@@ -2761,6 +3468,35 @@ function createHlsAdPlayer(contentVideo, options) {
2761
3468
  isAdPlaying: function isAdPlaying() {
2762
3469
  return adPlaying;
2763
3470
  },
3471
+ setFunnelContext: function setFunnelContext(context) {
3472
+ funnelContext = _object_spread({}, context);
3473
+ },
3474
+ abortPendingRequest: function abortPendingRequest() {
3475
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3476
+ if (pendingVastRequests.size === 0) return;
3477
+ pendingRequestAbortReason = reason;
3478
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3479
+ try {
3480
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3481
+ var controller = _step.value;
3482
+ controller.abort();
3483
+ }
3484
+ } catch (err) {
3485
+ _didIteratorError = true;
3486
+ _iteratorError = err;
3487
+ } finally{
3488
+ try {
3489
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3490
+ _iterator.return();
3491
+ }
3492
+ } finally{
3493
+ if (_didIteratorError) {
3494
+ throw _iteratorError;
3495
+ }
3496
+ }
3497
+ }
3498
+ pendingVastRequests.clear();
3499
+ },
2764
3500
  resize: function resize(width, height) {
2765
3501
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2766
3502
  if (adContainerEl) {
@@ -2796,6 +3532,13 @@ function createHlsAdPlayer(contentVideo, options) {
2796
3532
  if (adVideoElement && adPlaying) {
2797
3533
  var clamped = Math.max(0, Math.min(1, volume));
2798
3534
  adVideoElement.volume = clamped;
3535
+ var userActivation = navigator.userActivation;
3536
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3537
+ logFunnel("unmute_blocked_without_gesture", {
3538
+ requestedVolume: clamped
3539
+ });
3540
+ return;
3541
+ }
2799
3542
  adVideoElement.muted = clamped === 0;
2800
3543
  }
2801
3544
  },
@@ -4902,6 +5645,21 @@ function normalizeVastTagUrl(raw) {
4902
5645
  return raw;
4903
5646
  }
4904
5647
  }
5648
+ var GAM_AD_HOSTS = /* @__PURE__ */ new Set([
5649
+ "pubads.g.doubleclick.net",
5650
+ "securepubads.g.doubleclick.net"
5651
+ ]);
5652
+ function ensureVideoAdType(rawUrl) {
5653
+ try {
5654
+ var url = new URL(rawUrl);
5655
+ if (!GAM_AD_HOSTS.has(url.hostname)) return rawUrl;
5656
+ if (url.searchParams.has("ad_type")) return rawUrl;
5657
+ url.searchParams.set("ad_type", "video");
5658
+ return url.toString();
5659
+ } catch (unused) {
5660
+ return rawUrl;
5661
+ }
5662
+ }
4905
5663
  function applyVastMacros(baseUrl, ctx) {
4906
5664
  var expandedUrl = expandInlineMacroPlaceholders(baseUrl, ctx);
4907
5665
  var url;
@@ -6612,7 +7370,7 @@ var AdConfigManager = /*#__PURE__*/ function() {
6612
7370
  } : {}), {
6613
7371
  consent: this.consentSignals
6614
7372
  }));
6615
- var finalUrl = palNonce.injectNonce(urlWithMacros);
7373
+ var finalUrl = palNonce.injectNonce(ensureVideoAdType(urlWithMacros));
6616
7374
  console.log("[StormcloudVideoPlayer] Resolved optimized-pod request URL (pod=".concat(this.podCounter, ", pmad=").concat(podParams.maxAds, ", pmnd=").concat(podParams.minDurationMs, ", pmxd=").concat((_podParams_maxDurationMs = podParams.maxDurationMs) !== null && _podParams_maxDurationMs !== void 0 ? _podParams_maxDurationMs : "?", "):"), finalUrl);
6617
7375
  return finalUrl;
6618
7376
  }
@@ -6859,7 +7617,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6859
7617
  {
6860
7618
  key: "adFitsRemainingBudget",
6861
7619
  value: function adFitsRemainingBudget(durationMs) {
6862
- if (durationMs <= 0) {
7620
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6863
7621
  return true;
6864
7622
  }
6865
7623
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6918,6 +7676,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6918
7676
  value: function markAdStarted() {
6919
7677
  this.currentAdIndex++;
6920
7678
  this.totalAdsInBreak = this.currentAdIndex;
7679
+ }
7680
+ },
7681
+ {
7682
+ key: "noteAdRequestSent",
7683
+ value: function noteAdRequestSent() {
6921
7684
  this.totalAdRequestsInBreak++;
6922
7685
  this.lastAdRequestTime = Date.now();
6923
7686
  }
@@ -6969,6 +7732,9 @@ var AdTimingService = /*#__PURE__*/ function() {
6969
7732
  if (message.includes("timeout")) {
6970
7733
  return true;
6971
7734
  }
7735
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7736
+ return true;
7737
+ }
6972
7738
  if (message.includes("rate limit") || message.includes("too many requests")) {
6973
7739
  return true;
6974
7740
  }
@@ -8093,6 +8859,18 @@ function resizePlayer(video, adPlayer, debug) {
8093
8859
  }
8094
8860
  }
8095
8861
  // src/player/AdBreakOrchestrator.ts
8862
+ var REQUEST_FAILURE_STAGES = /* @__PURE__ */ new Set([
8863
+ "no_fill",
8864
+ "vast_fill_rejected",
8865
+ "request_failed",
8866
+ "media_unsupported",
8867
+ "play_failed",
8868
+ "play_resolved_but_never_started",
8869
+ "hls_fatal",
8870
+ "media_error",
8871
+ "stall",
8872
+ "decode_failure"
8873
+ ]);
8096
8874
  var AdBreakOrchestrator = /*#__PURE__*/ function() {
8097
8875
  function AdBreakOrchestrator(host, timing, adConfig, cueManager, placeholder) {
8098
8876
  _class_call_check(this, AdBreakOrchestrator);
@@ -8100,11 +8878,17 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8100
8878
  this.showAds = false;
8101
8879
  this.isShowingPlaceholder = false;
8102
8880
  this.adDetectSentForCurrentBreak = false;
8103
- this.continuousFetchingActive = false;
8104
- this.continuousFetchLoopRunning = false;
8105
- this.adRequestQueue = [];
8881
+ this.slotState = "IDLE";
8882
+ this.unusableResponsesInBreak = 0;
8883
+ this.controllerGeneration = 0;
8884
+ this.requestDiagnostics = /* @__PURE__ */ new Map();
8885
+ this.breakFunnel = {};
8886
+ this.controllerCallInFlight = false;
8887
+ this.playbackStartedForCurrentRequest = false;
8888
+ this.opportunityEpoch = -1;
8106
8889
  this.adPodQueue = [];
8107
- this.maxPlaceholderDurationMs = 5e3;
8890
+ this.defaultMinRemainingMsToRequestAd = 1e4;
8891
+ this.defaultMaxNoFillsPerBreak = 2;
8108
8892
  this.pendingAdBreak = null;
8109
8893
  this.host = host;
8110
8894
  this.timing = timing;
@@ -8140,7 +8924,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8140
8924
  key: "attachImaEventListeners",
8141
8925
  value: function attachImaEventListeners() {
8142
8926
  var _this = this;
8143
- var adPlayer = this.host.getAdPlayer();
8927
+ var controller = this.host.getAdPlayer();
8928
+ var generation = this.controllerGeneration;
8929
+ var adPlayer = {
8930
+ on: function on(event, handler) {
8931
+ controller.on(event, function(payload) {
8932
+ if (generation !== _this.controllerGeneration) {
8933
+ _this.logOrchestratorFunnel("stale_callback_ignored", {
8934
+ event: event,
8935
+ staleControllerId: generation,
8936
+ currentControllerId: _this.controllerGeneration
8937
+ });
8938
+ return;
8939
+ }
8940
+ handler(payload);
8941
+ });
8942
+ }
8943
+ };
8144
8944
  adPlayer.on("pod_ad_started", function(payload) {
8145
8945
  _this.timing.notePodAdStarted();
8146
8946
  if (_this.debug) {
@@ -8154,7 +8954,35 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8154
8954
  adPlayer.on("ad_interaction", function(event) {
8155
8955
  if (event) _this.host.onAdInteraction(event);
8156
8956
  });
8957
+ adPlayer.on("ad_funnel", function(payload) {
8958
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
8959
+ var stage = payload.stage;
8960
+ _this.countFunnelStage(stage);
8961
+ if (payload.reason) {
8962
+ _this.countFunnelStage("".concat(stage, ":").concat(payload.reason));
8963
+ }
8964
+ if (stage === "impression_fired" && payload.pixelCount != null) {
8965
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
8966
+ }
8967
+ if (payload.visibilityState === "hidden") {
8968
+ _this.countFunnelStage("while_hidden");
8969
+ }
8970
+ if (stage === "gam_http_request_sent") {
8971
+ if (payload.attempt === 1) {
8972
+ _this.timing.noteAdRequestSent();
8973
+ } else {
8974
+ _this.countFunnelStage("gam_http_request_retry");
8975
+ }
8976
+ }
8977
+ _this.recordRequestDiagnostic(payload);
8978
+ });
8157
8979
  adPlayer.on("ad_impression", function() {
8980
+ _this.timing.consecutiveFailures = 0;
8981
+ _this.setSlotState("PLAYING", "impression");
8982
+ if (!_this.playbackStartedForCurrentRequest) {
8983
+ _this.playbackStartedForCurrentRequest = true;
8984
+ _this.timing.markAdStarted();
8985
+ }
8158
8986
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8159
8987
  source: "hls",
8160
8988
  adIndex: _this.timing.currentAdIndex
@@ -8169,16 +8997,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8169
8997
  var remaining = _this.timing.getRemainingAdMs();
8170
8998
  _this.timing.consecutiveFailures = 0;
8171
8999
  if (_this.debug) {
8172
- console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8173
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8174
- } : {});
9000
+ console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms"));
8175
9001
  }
8176
9002
  if (_this.inAdBreak) {
8177
- if (_this.timing.hasTimeToStartAnotherAd()) {
8178
- _this.tryNextAvailableAdWithRateLimit();
8179
- } else {
8180
- _this.handleAdPodComplete();
8181
- }
9003
+ _this.setSlotState("NEEDS_NEXT_AD", "all_ads_completed");
9004
+ _this.requestNextAd("all_ads_completed");
8182
9005
  }
8183
9006
  });
8184
9007
  adPlayer.on("ad_error", function(errorPayload) {
@@ -8198,7 +9021,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8198
9021
  }
8199
9022
  }
8200
9023
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8201
- _this.handleAdFailure();
9024
+ if (_this.controllerCallInFlight) {
9025
+ return;
9026
+ }
9027
+ _this.handleAdFailure("ad_error");
8202
9028
  });
8203
9029
  adPlayer.on("content_pause", function() {
8204
9030
  _this.timing.clearAdFailsafeTimer();
@@ -8237,26 +9063,32 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8237
9063
  }
8238
9064
  _this.timing.consecutiveFailures = 0;
8239
9065
  _this.timing.recordPlayedAdDuration(_this.host.getAdPlayer());
8240
- var remaining = _this.timing.getRemainingAdMs();
8241
9066
  if (_this.debug) {
8242
- console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8243
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8244
- } : {});
8245
- }
8246
- if (_this.timing.hasTimeToStartAnotherAd()) {
8247
- _this.tryNextAvailableAdWithRateLimit();
8248
- } else {
8249
- _this.handleAdPodComplete();
9067
+ console.log("[AdBreak] content_resume: remaining=".concat(_this.timing.getRemainingAdMs(), "ms"));
8250
9068
  }
9069
+ _this.setSlotState("NEEDS_NEXT_AD", "ad_complete");
9070
+ _this.requestNextAd("ad_complete");
8251
9071
  });
8252
9072
  }
8253
9073
  },
8254
9074
  {
8255
9075
  key: "recreateAdController",
8256
- value: function recreateAdController() {
8257
- if (this.debug) {
8258
- console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");
9076
+ value: function recreateAdController(reason) {
9077
+ if (reason === "new_request" && (this.slotState === "REQUESTING" || this.slotState === "READY")) {
9078
+ console.warn("[AD-CONTROLLER] destroy during active request", {
9079
+ controllerId: this.controllerGeneration,
9080
+ requestId: this.currentRequestId,
9081
+ state: this.slotState,
9082
+ reason: reason
9083
+ });
8259
9084
  }
9085
+ console.log("[AD-CONTROLLER] destroy", {
9086
+ controllerId: this.controllerGeneration,
9087
+ requestId: this.currentRequestId,
9088
+ state: this.slotState,
9089
+ reason: reason
9090
+ });
9091
+ this.countFunnelStage("controller_destroy:".concat(reason));
8260
9092
  var shouldShowPlaceholder = this.inAdBreak && this.showAds;
8261
9093
  var adPlayer = this.host.getAdPlayer();
8262
9094
  if (shouldShowPlaceholder && adPlayer) {
@@ -8269,6 +9101,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8269
9101
  }
8270
9102
  var preservedMutedState = adPlayer.getOriginalMutedState();
8271
9103
  var preservedVolumeState = adPlayer.getOriginalVolume();
9104
+ this.playbackStartedForCurrentRequest = false;
8272
9105
  if (adPlayer) {
8273
9106
  try {
8274
9107
  adPlayer.destroy();
@@ -8282,9 +9115,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8282
9115
  var continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();
8283
9116
  var newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);
8284
9117
  this.host.setAdPlayer(newAdPlayer);
9118
+ this.controllerGeneration++;
8285
9119
  newAdPlayer.initialize();
8286
9120
  newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);
8287
9121
  this.attachImaEventListeners();
9122
+ if (this.debug) {
9123
+ console.log("[AD-CONTROLLER] create", {
9124
+ controllerId: this.controllerGeneration,
9125
+ reason: reason
9126
+ });
9127
+ }
8288
9128
  if (shouldShowPlaceholder) {
8289
9129
  this.placeholder.show();
8290
9130
  newAdPlayer.showPlaceholder();
@@ -8305,32 +9145,57 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8305
9145
  }
8306
9146
  },
8307
9147
  {
8308
- key: "handleAdStart",
8309
- value: // ───────────────────────────────────────────────────────────────
9148
+ // ───────────────────────────────────────────────────────────────
8310
9149
  // Ad break start
8311
9150
  // ───────────────────────────────────────────────────────────────
8312
- function handleAdStart(_marker) {
9151
+ key: "isBreakActive",
9152
+ value: function isBreakActive() {
9153
+ return this.slotState !== "IDLE";
9154
+ }
9155
+ },
9156
+ {
9157
+ key: "getSlotState",
9158
+ value: function getSlotState() {
9159
+ return this.slotState;
9160
+ }
9161
+ },
9162
+ {
9163
+ key: "beginVmapBreak",
9164
+ value: function beginVmapBreak(breakKey) {
9165
+ this.breakSource = "vmap";
9166
+ this.followUpBaseVastUrl = void 0;
9167
+ this.unusableResponsesInBreak = 0;
9168
+ this.timing.totalAdRequestsInBreak = 0;
9169
+ this.setSlotState("NEEDS_NEXT_AD", "vmap_break_start");
9170
+ this.noteOpportunity("vmap", breakKey);
9171
+ }
9172
+ },
9173
+ {
9174
+ key: "handleAdStart",
9175
+ value: function handleAdStart(marker) {
8313
9176
  return _async_to_generator(function() {
8314
- var scheduled, tags, baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, podPlayed;
9177
+ var baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, epoch, podPlayed;
8315
9178
  return _ts_generator(this, function(_state) {
8316
9179
  switch(_state.label){
8317
9180
  case 0:
8318
- scheduled = this.adConfig.findCurrentOrNextBreak(this.host.video.currentTime * 1e3);
8319
- if (scheduled) {
8320
- this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));
9181
+ if (this.slotState !== "IDLE") {
9182
+ this.logOrchestratorFunnel("duplicate_break_start", {
9183
+ source: "scte35",
9184
+ state: this.slotState
9185
+ });
9186
+ return [
9187
+ 2
9188
+ ];
8321
9189
  }
8322
- tags = this.adConfig.selectVastTagsForBreak(scheduled);
8323
- if (tags && tags.length > 0 && tags[0]) {
8324
- baseVastUrl = tags[0];
8325
- } else if (this.adConfig.apiVastTagUrl) {
8326
- baseVastUrl = this.adConfig.apiVastTagUrl;
8327
- } else {
9190
+ baseVastUrl = this.adConfig.apiVastTagUrl;
9191
+ if (!baseVastUrl) {
9192
+ console.warn("[AdBreak] SCTE-35 break started but no direct VAST tag is configured");
8328
9193
  this.clearPendingAdBreak();
8329
9194
  return [
8330
9195
  2
8331
9196
  ];
8332
9197
  }
8333
- adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled === null || scheduled === void 0 ? void 0 : scheduled.durationMs;
9198
+ adBreakDurationMs = marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.timing.expectedAdBreakDurationMs;
8334
9199
  if (this.debug) {
8335
9200
  mode = this.host.config.isLiveStream ? "LIVE" : "VOD";
8336
9201
  console.log("[CONTINUOUS-FETCH] ".concat(mode, " MODE: Target duration=").concat(adBreakDurationMs, "ms"));
@@ -8338,9 +9203,12 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8338
9203
  this.timing.failedVastUrls.clear();
8339
9204
  this.timing.temporaryFailureUrls.clear();
8340
9205
  this.timing.consecutiveFailures = 0;
8341
- this.continuousFetchingActive = true;
8342
9206
  this.isShowingPlaceholder = false;
8343
9207
  this.timing.totalAdRequestsInBreak = 0;
9208
+ this.breakSource = "scte35";
9209
+ this.followUpBaseVastUrl = baseVastUrl;
9210
+ this.unusableResponsesInBreak = 0;
9211
+ this.setSlotState("NEEDS_NEXT_AD", "scte35_break_start");
8344
9212
  if (this.adConfig.podAssignedByPrefetch) {
8345
9213
  this.adConfig.podAssignedByPrefetch = false;
8346
9214
  } else {
@@ -8358,29 +9226,18 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8358
9226
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8359
9227
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8360
9228
  }
9229
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
9230
+ epoch = this.timing.adBreakEpoch;
8361
9231
  return [
8362
9232
  4,
8363
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
9233
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8364
9234
  ];
8365
9235
  case 1:
8366
9236
  podPlayed = _state.sent();
8367
- if (!!podPlayed) return [
8368
- 3,
8369
- 3
8370
- ];
8371
- if (this.debug) {
8372
- console.log("[POD] Initial pod request did not fill; attempting top-up pod request");
9237
+ if (!podPlayed && this.inAdBreak && epoch === this.timing.adBreakEpoch) {
9238
+ this.setSlotState("NEEDS_NEXT_AD", "initial_request_failed");
9239
+ this.requestNextAd("initial_request_failed");
8373
9240
  }
8374
- this.continuousFetchingActive = true;
8375
- this.startContinuousFetching(baseVastUrl);
8376
- return [
8377
- 4,
8378
- this.tryNextAvailableAdWithRateLimit()
8379
- ];
8380
- case 2:
8381
- _state.sent();
8382
- _state.label = 3;
8383
- case 3:
8384
9241
  return [
8385
9242
  2
8386
9243
  ];
@@ -8394,12 +9251,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8394
9251
  value: // ───────────────────────────────────────────────────────────────
8395
9252
  // Optimized pod (single multi-ad request)
8396
9253
  // ───────────────────────────────────────────────────────────────
8397
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
9254
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8398
9255
  return _async_to_generator(function() {
8399
- var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
9256
+ var podUrl, prefetched, epoch, generation, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8400
9257
  return _ts_generator(this, function(_state) {
8401
9258
  switch(_state.label){
8402
9259
  case 0:
9260
+ prefetched = !!(this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0);
8403
9261
  if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {
8404
9262
  podUrl = this.pendingAdBreak.vastUrls[0];
8405
9263
  this.clearPendingAdBreak();
@@ -8412,12 +9270,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8412
9270
  false
8413
9271
  ];
8414
9272
  }
8415
- this.continuousFetchingActive = false;
8416
- this.recreateAdController();
9273
+ this.noteVastUrlGenerated(podUrl, prefetched ? "prefetch" : "break_start");
9274
+ epoch = this.timing.adBreakEpoch;
9275
+ this.recreateAdController("new_request");
9276
+ generation = this.controllerGeneration;
8417
9277
  adPlayer = this.host.getAdPlayer();
8418
9278
  requestToken = ++this.timing.adRequestTokenCounter;
8419
9279
  this.timing.activeAdRequestToken = requestToken;
8420
9280
  this.currentVastUrl = podUrl;
9281
+ this.setSlotState("REQUESTING", "initial_pod");
9282
+ this.beginFunnelRequest(adPlayer, requestToken, "initial_pod");
8421
9283
  _state.label = 1;
8422
9284
  case 1:
8423
9285
  _state.trys.push([
@@ -8432,16 +9294,24 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8432
9294
  ];
8433
9295
  case 2:
8434
9296
  _state.sent();
9297
+ if (this.isStale(epoch, generation)) return [
9298
+ 2,
9299
+ true
9300
+ ];
8435
9301
  this.timing.startAdRequestWatchdog(requestToken);
8436
- this.timing.lastAdRequestTime = Date.now();
8437
9302
  return [
8438
9303
  4,
8439
- adPlayer.requestAds(podUrl)
9304
+ this.callController(function() {
9305
+ return adPlayer.requestAds(podUrl);
9306
+ })
8440
9307
  ];
8441
9308
  case 3:
8442
9309
  _state.sent();
8443
9310
  this.timing.clearAdRequestWatchdog();
8444
- if (this.timing.activeAdRequestToken !== requestToken) {
9311
+ if (this.isStale(epoch, generation)) {
9312
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9313
+ requestId: requestToken
9314
+ });
8445
9315
  return [
8446
9316
  2,
8447
9317
  true
@@ -8449,11 +9319,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8449
9319
  }
8450
9320
  podCount = (_ref = (_adPlayer_getPodAdCount = adPlayer.getPodAdCount) === null || _adPlayer_getPodAdCount === void 0 ? void 0 : _adPlayer_getPodAdCount.call(adPlayer)) !== null && _ref !== void 0 ? _ref : 1;
8451
9321
  if (podCount < 1) {
9322
+ if (this.timing.activeAdRequestToken === requestToken) {
9323
+ this.timing.activeAdRequestToken = null;
9324
+ }
9325
+ this.recordRequestFailure(new Error("No ads available"), podUrl);
8452
9326
  return [
8453
9327
  2,
8454
9328
  false
8455
9329
  ];
8456
9330
  }
9331
+ this.setSlotState("READY", "vast_ready");
8457
9332
  if (this.debug) {
8458
9333
  console.log(podCount === 1 ? "[POD] Response contained a single ad; playing it and enabling pod top-up" : "[POD] Optimized pod returned ".concat(podCount, " ads; playing pod in one controller"));
8459
9334
  }
@@ -8465,18 +9340,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8465
9340
  this.timing.startAdFailsafeTimer(requestToken);
8466
9341
  return [
8467
9342
  4,
8468
- adPlayer.play()
9343
+ this.callController(function() {
9344
+ return adPlayer.play();
9345
+ })
8469
9346
  ];
8470
9347
  case 4:
8471
9348
  _state.sent();
8472
- this.timing.markAdStarted();
9349
+ if (this.isStale(epoch, generation)) return [
9350
+ 2,
9351
+ true
9352
+ ];
8473
9353
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8474
9354
  this.timing.scheduleAdStopAtBreakBoundary();
8475
9355
  }
8476
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8477
- this.timing.consecutiveFailures = 0;
8478
- this.continuousFetchingActive = true;
8479
- this.startContinuousFetching(baseVastUrl);
9356
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8480
9357
  return [
8481
9358
  2,
8482
9359
  true
@@ -8488,14 +9365,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8488
9365
  if (this.timing.activeAdRequestToken === requestToken) {
8489
9366
  this.timing.activeAdRequestToken = null;
8490
9367
  }
9368
+ if (this.isStale(epoch, generation)) {
9369
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9370
+ requestId: requestToken,
9371
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
9372
+ });
9373
+ return [
9374
+ 2,
9375
+ true
9376
+ ];
9377
+ }
8491
9378
  if (this.debug) {
8492
9379
  console.warn("[POD] Optimized pod request/play failed:", error);
8493
9380
  }
8494
- if (this.timing.isTemporaryAdError(error)) {
8495
- this.timing.temporaryFailureUrls.set(podUrl, Date.now());
8496
- }
8497
- this.continuousFetchingActive = true;
8498
- this.recreateAdController();
9381
+ this.recordRequestFailure(error, podUrl);
8499
9382
  return [
8500
9383
  2,
8501
9384
  false
@@ -8511,168 +9394,204 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8511
9394
  },
8512
9395
  {
8513
9396
  // ───────────────────────────────────────────────────────────────
8514
- // Continuous fetching
9397
+ // Next-ad scheduling (single flight)
8515
9398
  // ───────────────────────────────────────────────────────────────
8516
- key: "startContinuousFetching",
8517
- value: function startContinuousFetching(baseVastUrl) {
8518
- if (!this.continuousFetchingActive) {
9399
+ key: "setSlotState",
9400
+ value: function setSlotState(next, reason) {
9401
+ if (this.slotState === next) return;
9402
+ var previous = this.slotState;
9403
+ this.slotState = next;
9404
+ if (this.debug) {
9405
+ console.log("[AdBreak][STATE] ".concat(previous, " -> ").concat(next), {
9406
+ reason: reason,
9407
+ breakId: this.timing.adBreakEpoch,
9408
+ requestId: this.currentRequestId,
9409
+ controllerId: this.controllerGeneration
9410
+ });
9411
+ }
9412
+ }
9413
+ },
9414
+ {
9415
+ key: "isStale",
9416
+ value: function isStale(epoch, generation) {
9417
+ return !this.inAdBreak || epoch !== this.timing.adBreakEpoch || generation !== this.controllerGeneration;
9418
+ }
9419
+ },
9420
+ {
9421
+ key: "getMinRemainingMsToRequestAd",
9422
+ value: function getMinRemainingMsToRequestAd() {
9423
+ var configured = this.host.config.minRemainingMsToRequestAd;
9424
+ var floor = this.timing.getMinRemainingMsToStartAd();
9425
+ if (typeof configured === "number" && configured >= 0) {
9426
+ return Math.max(configured, floor);
9427
+ }
9428
+ return Math.max(this.defaultMinRemainingMsToRequestAd, floor);
9429
+ }
9430
+ },
9431
+ {
9432
+ key: "getMaxNoFillsPerBreak",
9433
+ value: function getMaxNoFillsPerBreak() {
9434
+ var configured = this.host.config.maxNoFillsPerBreak;
9435
+ return typeof configured === "number" && configured > 0 ? configured : this.defaultMaxNoFillsPerBreak;
9436
+ }
9437
+ },
9438
+ {
9439
+ key: "isBreakTimeBounded",
9440
+ value: function isBreakTimeBounded() {
9441
+ return this.breakSource === "scte35" || this.timing.expectedAdBreakDurationMs != null;
9442
+ }
9443
+ },
9444
+ {
9445
+ key: "getStopRequestingReason",
9446
+ value: function getStopRequestingReason(remainingMs) {
9447
+ if (this.breakSource === "vmap") {
9448
+ if (this.adPodQueue.length === 0) return "vmap_queue_empty";
9449
+ } else if (this.breakSource !== "scte35" || !this.followUpBaseVastUrl) {
9450
+ return "no_follow_up_source";
9451
+ }
9452
+ if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9453
+ return "max_consecutive_failures";
9454
+ }
9455
+ if (this.unusableResponsesInBreak >= this.getMaxNoFillsPerBreak()) {
9456
+ return "unusable_response_limit";
9457
+ }
9458
+ if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {
9459
+ return "request_cap";
9460
+ }
9461
+ if (this.timing.isGamInCooldown()) {
9462
+ return "gam_cooldown";
9463
+ }
9464
+ if (this.isBreakTimeBounded() && remainingMs < this.getMinRemainingMsToRequestAd()) {
9465
+ return "insufficient_break_time";
9466
+ }
9467
+ return void 0;
9468
+ }
9469
+ },
9470
+ {
9471
+ key: "getNextRequestDelayMs",
9472
+ value: function getNextRequestDelayMs() {
9473
+ var failures = this.timing.consecutiveFailures;
9474
+ var backoff = failures > 0 ? Math.min(this.timing.backoffBaseMs * Math.pow(2, failures), this.timing.maxBackoffMs) : 0;
9475
+ var minInterval = this.timing.minAdRequestIntervalMs + backoff;
9476
+ var sinceLast = Date.now() - this.timing.lastAdRequestTime;
9477
+ return Math.max(0, minInterval - sinceLast);
9478
+ }
9479
+ },
9480
+ {
9481
+ key: "requestNextAd",
9482
+ value: function requestNextAd(trigger) {
9483
+ var _this = this;
9484
+ if (!this.inAdBreak) return;
9485
+ if (this.slotState !== "NEEDS_NEXT_AD") {
9486
+ this.logOrchestratorFunnel("request_suppressed", {
9487
+ trigger: trigger,
9488
+ state: this.slotState,
9489
+ why: "slot_busy"
9490
+ });
8519
9491
  return;
8520
9492
  }
8521
- if (this.continuousFetchLoopRunning) {
8522
- if (this.debug) {
8523
- console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start");
8524
- }
9493
+ if (this.nextAdTimerId != null) {
9494
+ this.logOrchestratorFunnel("request_suppressed", {
9495
+ trigger: trigger,
9496
+ state: this.slotState,
9497
+ why: "request_already_scheduled"
9498
+ });
8525
9499
  return;
8526
9500
  }
8527
- if (this.debug) {
8528
- console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop");
9501
+ var remainingMs = this.timing.getRemainingAdMs();
9502
+ var stopReason = this.getStopRequestingReason(remainingMs);
9503
+ if (stopReason) {
9504
+ this.logOrchestratorFunnel("next_ad_decision", {
9505
+ trigger: trigger,
9506
+ decision: "end_break",
9507
+ reason: stopReason,
9508
+ remainingMs: remainingMs,
9509
+ requestsSent: this.timing.totalAdRequestsInBreak,
9510
+ unusableResponses: this.unusableResponsesInBreak,
9511
+ consecutiveFailures: this.timing.consecutiveFailures
9512
+ });
9513
+ this.handleAdPodComplete(stopReason);
9514
+ return;
9515
+ }
9516
+ var waitMs = this.getNextRequestDelayMs();
9517
+ if (waitMs > 0 && this.isBreakTimeBounded() && remainingMs - waitMs < this.getMinRemainingMsToRequestAd()) {
9518
+ this.logOrchestratorFunnel("next_ad_decision", {
9519
+ trigger: trigger,
9520
+ decision: "end_break",
9521
+ reason: "insufficient_break_time_after_backoff",
9522
+ remainingMs: remainingMs,
9523
+ waitMs: waitMs
9524
+ });
9525
+ this.handleAdPodComplete("insufficient_break_time_after_backoff");
9526
+ return;
9527
+ }
9528
+ this.logOrchestratorFunnel("next_ad_decision", {
9529
+ trigger: trigger,
9530
+ decision: waitMs > 0 ? "request_after_delay" : "request_now",
9531
+ waitMs: waitMs,
9532
+ remainingMs: remainingMs,
9533
+ consecutiveFailures: this.timing.consecutiveFailures
9534
+ });
9535
+ if (waitMs > 0) {
9536
+ if (!this.isShowingPlaceholder) {
9537
+ this.isShowingPlaceholder = true;
9538
+ this.host.getAdPlayer().showPlaceholder();
9539
+ }
9540
+ var epoch = this.timing.adBreakEpoch;
9541
+ this.nextAdTimerId = window.setTimeout(function() {
9542
+ _this.nextAdTimerId = void 0;
9543
+ if (!_this.inAdBreak || epoch !== _this.timing.adBreakEpoch) return;
9544
+ _this.requestNextAd("".concat(trigger, ":after_delay"));
9545
+ }, waitMs);
9546
+ return;
8529
9547
  }
8530
- this.continuousFetchLoopRunning = true;
8531
- this.continuousFetchLoop(baseVastUrl);
9548
+ void this.requestFollowUpAd(trigger);
8532
9549
  }
8533
9550
  },
8534
9551
  {
8535
- key: "continuousFetchLoop",
8536
- value: function continuousFetchLoop(baseVastUrl) {
9552
+ key: "requestFollowUpAd",
9553
+ value: function requestFollowUpAd(trigger) {
8537
9554
  return _async_to_generator(function() {
8538
- var _this, _loop, epoch, _ret;
9555
+ var url, epoch, unused;
8539
9556
  return _ts_generator(this, function(_state) {
8540
9557
  switch(_state.label){
8541
9558
  case 0:
8542
- _loop = function() {
8543
- var remaining, maxQueueSize, newAdUrl, queuedUrlsPreview, generationDelay;
8544
- return _ts_generator(this, function(_state) {
8545
- switch(_state.label){
8546
- case 0:
8547
- remaining = Math.min(_this.timing.getWallClockRemainingAdMs(), _this.timing.getDurationBudgetRemainingMs());
8548
- if (remaining <= _this.timing.getMinRemainingMsToStartAd()) {
8549
- if (_this.debug) {
8550
- console.log("[CONTINUOUS-FETCH] Not enough ad break time left (wall=".concat(_this.timing.getWallClockRemainingAdMs(), "ms, budget=").concat(_this.timing.getDurationBudgetRemainingMs(), "ms), stopping URL generation"));
8551
- }
8552
- return [
8553
- 2,
8554
- "break"
8555
- ];
8556
- }
8557
- if (_this.timing.isGamInCooldown()) {
8558
- if (_this.debug) {
8559
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation");
8560
- }
8561
- return [
8562
- 2,
8563
- "break"
8564
- ];
8565
- }
8566
- if (_this.timing.consecutiveFailures >= _this.timing.maxConsecutiveFailures) {
8567
- if (_this.debug) {
8568
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(_this.timing.consecutiveFailures, "), stopping URL generation"));
8569
- }
8570
- return [
8571
- 2,
8572
- "break"
8573
- ];
8574
- }
8575
- if (_this.timing.totalAdRequestsInBreak >= _this.timing.maxTotalAdRequestsPerBreak) {
8576
- if (_this.debug) {
8577
- console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(_this.timing.maxTotalAdRequestsPerBreak, "), stopping"));
8578
- }
8579
- return [
8580
- 2,
8581
- "break"
8582
- ];
8583
- }
8584
- maxQueueSize = 5;
8585
- if (!(_this.adRequestQueue.length >= maxQueueSize)) return [
8586
- 3,
8587
- 2
8588
- ];
8589
- if (_this.debug) {
8590
- console.log("[CONTINUOUS-FETCH] URL queue full (".concat(_this.adRequestQueue.length, "), waiting..."));
8591
- }
8592
- return [
8593
- 4,
8594
- new Promise(function(resolve) {
8595
- return setTimeout(resolve, 1e3);
8596
- })
8597
- ];
8598
- case 1:
8599
- _state.sent();
8600
- return [
8601
- 2,
8602
- "continue"
8603
- ];
8604
- case 2:
8605
- newAdUrl = _this.nextAdRequestUrl(baseVastUrl);
8606
- if (!(!newAdUrl || _this.timing.failedVastUrls.has(newAdUrl) || _this.timing.isUrlInCooldown(newAdUrl))) return [
8607
- 3,
8608
- 4
8609
- ];
8610
- return [
8611
- 4,
8612
- new Promise(function(resolve) {
8613
- return setTimeout(resolve, 500);
8614
- })
8615
- ];
8616
- case 3:
8617
- _state.sent();
8618
- return [
8619
- 2,
8620
- "continue"
8621
- ];
8622
- case 4:
8623
- if (_this.debug) {
8624
- queuedUrlsPreview = _to_consumable_array(_this.adRequestQueue).concat([
8625
- newAdUrl
8626
- ]);
8627
- console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(queuedUrlsPreview.length, ")"), {
8628
- queuedUrls: queuedUrlsPreview
8629
- });
8630
- }
8631
- _this.adRequestQueue.push(newAdUrl);
8632
- generationDelay = _this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, _this.timing.consecutiveFailures), 5e3) : 500;
8633
- return [
8634
- 4,
8635
- new Promise(function(resolve) {
8636
- return setTimeout(resolve, generationDelay);
8637
- })
8638
- ];
8639
- case 5:
8640
- _state.sent();
8641
- return [
8642
- 2
8643
- ];
8644
- }
8645
- });
8646
- };
9559
+ if (this.breakSource === "vmap") {
9560
+ url = this.adPodQueue.shift();
9561
+ } else if (this.followUpBaseVastUrl) {
9562
+ url = this.nextAdRequestUrl(this.followUpBaseVastUrl);
9563
+ }
9564
+ if (!url) return [
9565
+ 2
9566
+ ];
9567
+ this.noteVastUrlGenerated(ensureVideoAdType(url), trigger);
8647
9568
  epoch = this.timing.adBreakEpoch;
8648
9569
  _state.label = 1;
8649
9570
  case 1:
8650
- if (!(this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch)) return [
8651
- 3,
8652
- 3
8653
- ];
8654
- _this = this;
9571
+ _state.trys.push([
9572
+ 1,
9573
+ 3,
9574
+ ,
9575
+ 4
9576
+ ]);
8655
9577
  return [
8656
- 5,
8657
- _ts_values(_loop())
9578
+ 4,
9579
+ this.playSingleAd(url, trigger)
8658
9580
  ];
8659
9581
  case 2:
8660
- _ret = _state.sent();
8661
- if (_ret === "break") return [
9582
+ _state.sent();
9583
+ return [
8662
9584
  3,
8663
- 3
9585
+ 4
8664
9586
  ];
9587
+ case 3:
9588
+ unused = _state.sent();
9589
+ this.continueAfterRequestFailure(epoch);
8665
9590
  return [
8666
9591
  3,
8667
- 1
9592
+ 4
8668
9593
  ];
8669
- case 3:
8670
- this.continuousFetchLoopRunning = false;
8671
- if (this.debug) {
8672
- console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length, ")"), this.adRequestQueue.length > 0 ? {
8673
- queuedUrls: _to_consumable_array(this.adRequestQueue)
8674
- } : {});
8675
- }
9594
+ case 4:
8676
9595
  return [
8677
9596
  2
8678
9597
  ];
@@ -8682,236 +9601,318 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8682
9601
  }
8683
9602
  },
8684
9603
  {
8685
- key: "stopContinuousFetching",
8686
- value: function stopContinuousFetching() {
8687
- this.continuousFetchingActive = false;
8688
- this.continuousFetchLoopRunning = false;
8689
- this.placeholder.hide();
8690
- if (this.debug) {
8691
- console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching");
9604
+ key: "continueAfterRequestFailure",
9605
+ value: function continueAfterRequestFailure() {
9606
+ var epoch = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.timing.adBreakEpoch;
9607
+ if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) return;
9608
+ this.setSlotState("NEEDS_NEXT_AD", "request_failed");
9609
+ this.requestNextAd("after_failure");
9610
+ }
9611
+ },
9612
+ {
9613
+ key: "cancelScheduledRequest",
9614
+ value: function cancelScheduledRequest() {
9615
+ if (this.nextAdTimerId != null) {
9616
+ clearTimeout(this.nextAdTimerId);
9617
+ this.nextAdTimerId = void 0;
8692
9618
  }
8693
9619
  }
8694
9620
  },
8695
9621
  {
8696
- key: "tryNextAvailableAdWithRateLimit",
8697
- value: // ───────────────────────────────────────────────────────────────
8698
- // Ad iteration
9622
+ key: "noteVastUrlGenerated",
9623
+ value: function noteVastUrlGenerated(url, source) {
9624
+ var _ref, _ref1, _ref2, _ref3, _ref4;
9625
+ var params;
9626
+ try {
9627
+ params = new URL(url).searchParams;
9628
+ } catch (unused) {}
9629
+ var adType = (_ref = params === null || params === void 0 ? void 0 : params.get("ad_type")) !== null && _ref !== void 0 ? _ref : void 0;
9630
+ this.logOrchestratorFunnel("vast_url_generated", {
9631
+ source: source,
9632
+ pod: (_ref1 = params === null || params === void 0 ? void 0 : params.get("pod")) !== null && _ref1 !== void 0 ? _ref1 : void 0,
9633
+ pmad: (_ref2 = params === null || params === void 0 ? void 0 : params.get("pmad")) !== null && _ref2 !== void 0 ? _ref2 : void 0,
9634
+ pmnd: (_ref3 = params === null || params === void 0 ? void 0 : params.get("pmnd")) !== null && _ref3 !== void 0 ? _ref3 : void 0,
9635
+ pmxd: (_ref4 = params === null || params === void 0 ? void 0 : params.get("pmxd")) !== null && _ref4 !== void 0 ? _ref4 : void 0,
9636
+ adType: adType
9637
+ });
9638
+ if (adType === "audio" || adType === "audio_video") {
9639
+ console.warn("[AdBreak] VAST tag requests ad_type=".concat(adType, "; GAM may return audio-only creatives, which this video player rejects"));
9640
+ this.countFunnelStage("tag_allows_audio");
9641
+ }
9642
+ }
9643
+ },
9644
+ {
9645
+ key: "recordRequestFailure",
9646
+ value: function recordRequestFailure(error, vastTagUrl) {
9647
+ var _diag_vastAdCount;
9648
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
9649
+ var message = (error === null || error === void 0 ? void 0 : error.message) || "";
9650
+ var outcome;
9651
+ if (message.includes("ad_duration_exceeds_budget")) {
9652
+ outcome = "discarded_budget";
9653
+ } else if (message.includes("VAST fill rejected")) {
9654
+ outcome = "fill_rejected";
9655
+ } else if (/no ads available|no fill|nofill/i.test(message)) {
9656
+ outcome = "no_fill";
9657
+ } else if (/timeout/i.test(message)) {
9658
+ outcome = "request_timeout";
9659
+ } else if (/destroyed|aborted/i.test(message)) {
9660
+ outcome = "request_aborted";
9661
+ } else if (diag && ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired) {
9662
+ outcome = "playback_failed";
9663
+ } else {
9664
+ outcome = "request_failed";
9665
+ }
9666
+ this.timing.consecutiveFailures++;
9667
+ if (outcome === "no_fill" || outcome === "fill_rejected" || outcome === "discarded_budget") {
9668
+ this.unusableResponsesInBreak++;
9669
+ }
9670
+ if (outcome === "no_fill") {
9671
+ this.timing.recordGamNoFill();
9672
+ }
9673
+ if (diag && !diag.failureReason) {
9674
+ diag.failureReason = "".concat(outcome, ": ").concat(message);
9675
+ }
9676
+ if (this.timing.isTemporaryAdError(error)) {
9677
+ this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9678
+ } else if (outcome !== "discarded_budget") {
9679
+ this.timing.failedVastUrls.add(vastTagUrl);
9680
+ }
9681
+ this.countFunnelStage("request_outcome:".concat(outcome));
9682
+ this.logOrchestratorFunnel("request_outcome", {
9683
+ outcome: outcome,
9684
+ errorMessage: message,
9685
+ consecutiveFailures: this.timing.consecutiveFailures,
9686
+ unusableResponsesInBreak: this.unusableResponsesInBreak
9687
+ });
9688
+ }
9689
+ },
9690
+ {
8699
9691
  // ───────────────────────────────────────────────────────────────
8700
- function tryNextAvailableAdWithRateLimit() {
8701
- return _async_to_generator(function() {
8702
- var epoch, backoffMultiplier, backoffDelay, effectiveMinInterval, timeSinceLastRequest, waitTime;
8703
- return _ts_generator(this, function(_state) {
8704
- switch(_state.label){
8705
- case 0:
8706
- if (!this.inAdBreak) {
8707
- return [
8708
- 2
8709
- ];
8710
- }
8711
- epoch = this.timing.adBreakEpoch;
8712
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8713
- if (this.debug) {
8714
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
8715
- }
8716
- this.handleAdPodComplete();
8717
- return [
8718
- 2
8719
- ];
8720
- }
8721
- backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);
8722
- backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);
8723
- effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);
8724
- timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;
8725
- if (!(timeSinceLastRequest < effectiveMinInterval)) return [
8726
- 3,
8727
- 2
8728
- ];
8729
- waitTime = effectiveMinInterval - timeSinceLastRequest;
8730
- if (this.debug) {
8731
- console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(waitTime, "ms before next request (backoff: ").concat(this.timing.consecutiveFailures, " failures)"));
8732
- }
8733
- return [
8734
- 4,
8735
- new Promise(function(resolve) {
8736
- return setTimeout(resolve, waitTime);
8737
- })
8738
- ];
8739
- case 1:
8740
- _state.sent();
8741
- _state.label = 2;
8742
- case 2:
8743
- if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {
8744
- return [
8745
- 2
8746
- ];
8747
- }
8748
- return [
8749
- 2,
8750
- this.tryNextAvailableAd(0)
8751
- ];
9692
+ // Per-request diagnostics
9693
+ // ───────────────────────────────────────────────────────────────
9694
+ key: "recordRequestDiagnostic",
9695
+ value: function recordRequestDiagnostic(payload) {
9696
+ var requestId = payload.requestId;
9697
+ if (typeof requestId !== "number") return;
9698
+ var diag = this.requestDiagnostics.get(requestId);
9699
+ if (!diag) return;
9700
+ switch(payload.stage){
9701
+ case "gam_http_request_sent":
9702
+ diag.gamRequestSent++;
9703
+ break;
9704
+ case "gam_response_received":
9705
+ diag.vastHttpStatus = payload.httpStatus;
9706
+ break;
9707
+ case "vast_parsed":
9708
+ diag.vastAdCount = payload.adElementCount;
9709
+ break;
9710
+ case "wrapper_fetch":
9711
+ case "inline_resolved":
9712
+ if (typeof payload.depth === "number") {
9713
+ diag.wrapperDepth = Math.max(diag.wrapperDepth, payload.depth);
9714
+ }
9715
+ if (payload.stage === "inline_resolved") diag.inlineResolved = true;
9716
+ break;
9717
+ case "mediafile_evaluated":
9718
+ diag.mediaCandidateCount++;
9719
+ if (payload.whyAccepted) diag.supportedMediaCount++;
9720
+ break;
9721
+ case "playing":
9722
+ diag.playStarted = true;
9723
+ break;
9724
+ case "impression_fired":
9725
+ diag.impressionFired = true;
9726
+ break;
9727
+ default:
9728
+ if (REQUEST_FAILURE_STAGES.has(payload.stage) && !diag.failureReason) {
9729
+ diag.failureReason = payload.reason ? "".concat(payload.stage, ":").concat(payload.reason) : payload.stage;
8752
9730
  }
9731
+ }
9732
+ }
9733
+ },
9734
+ {
9735
+ key: "finalizeRequestDiagnostics",
9736
+ value: function finalizeRequestDiagnostics(requestId, endReason) {
9737
+ var _diag_vastAdCount;
9738
+ if (requestId == null) return;
9739
+ var diag = this.requestDiagnostics.get(requestId);
9740
+ if (!diag) return;
9741
+ this.requestDiagnostics.delete(requestId);
9742
+ if (!diag.impressionFired && !diag.failureReason && endReason) {
9743
+ diag.failureReason = endReason;
9744
+ }
9745
+ var gamReturnedAdWithoutImpression = ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired;
9746
+ if (gamReturnedAdWithoutImpression) {
9747
+ this.countFunnelStage("gam_ad_without_impression");
9748
+ }
9749
+ var startedAt = diag.startedAt, fields = _object_without_properties(diag, [
9750
+ "startedAt"
9751
+ ]);
9752
+ console.log("[AdBreak][REQUEST] summary", _object_spread_props(_object_spread({}, fields), {
9753
+ durationMs: Date.now() - startedAt,
9754
+ gamReturnedAdWithoutImpression: gamReturnedAdWithoutImpression
9755
+ }));
9756
+ }
9757
+ },
9758
+ {
9759
+ // ───────────────────────────────────────────────────────────────
9760
+ // Single ad playback
9761
+ // ───────────────────────────────────────────────────────────────
9762
+ key: "withCurrentPodBudget",
9763
+ value: function withCurrentPodBudget(rawVastTagUrl) {
9764
+ var vastTagUrl = ensureVideoAdType(rawVastTagUrl);
9765
+ var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
9766
+ if (!(remaining > 0)) return vastTagUrl;
9767
+ try {
9768
+ var url = new URL(vastTagUrl);
9769
+ if (!url.searchParams.has("pmxd")) return vastTagUrl;
9770
+ var maxMs = Math.round(remaining);
9771
+ url.searchParams.set("pmxd", String(maxMs));
9772
+ var minMs = Number(url.searchParams.get("pmnd"));
9773
+ if (Number.isFinite(minMs) && minMs > maxMs) {
9774
+ url.searchParams.set("pmnd", String(maxMs));
9775
+ }
9776
+ return url.toString();
9777
+ } catch (unused) {
9778
+ return vastTagUrl;
9779
+ }
9780
+ }
9781
+ },
9782
+ {
9783
+ key: "countFunnelStage",
9784
+ value: function countFunnelStage(stage) {
9785
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9786
+ var _this_breakFunnel_stage;
9787
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9788
+ }
9789
+ },
9790
+ {
9791
+ key: "logOrchestratorFunnel",
9792
+ value: function logOrchestratorFunnel(stage) {
9793
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9794
+ this.countFunnelStage(stage);
9795
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9796
+ breakId: this.timing.adBreakEpoch,
9797
+ requestId: this.currentRequestId,
9798
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9799
+ }, extra));
9800
+ }
9801
+ },
9802
+ {
9803
+ key: "noteOpportunity",
9804
+ value: function noteOpportunity(source, breakKey) {
9805
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9806
+ this.logOrchestratorFunnel("duplicate_break_start", {
9807
+ source: source,
9808
+ breakKey: breakKey
8753
9809
  });
8754
- }).call(this);
9810
+ return;
9811
+ }
9812
+ this.opportunityBreakKey = breakKey;
9813
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9814
+ this.logOrchestratorFunnel("opportunity_created", {
9815
+ source: source,
9816
+ breakKey: breakKey,
9817
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9818
+ });
9819
+ }
9820
+ },
9821
+ {
9822
+ key: "beginFunnelRequest",
9823
+ value: function beginFunnelRequest(adPlayer, requestToken, trigger) {
9824
+ var _adPlayer_setFunnelContext;
9825
+ if (this.controllerCallInFlight) {
9826
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9827
+ newRequestId: requestToken
9828
+ });
9829
+ }
9830
+ this.finalizeRequestDiagnostics(this.currentRequestId);
9831
+ this.currentRequestId = requestToken;
9832
+ this.requestStartedAt = Date.now();
9833
+ this.requestDiagnostics.set(requestToken, {
9834
+ breakId: this.timing.adBreakEpoch,
9835
+ requestId: requestToken,
9836
+ controllerId: this.controllerGeneration,
9837
+ trigger: trigger,
9838
+ gamRequestSent: 0,
9839
+ wrapperDepth: 0,
9840
+ inlineResolved: false,
9841
+ mediaCandidateCount: 0,
9842
+ supportedMediaCount: 0,
9843
+ playStarted: false,
9844
+ impressionFired: false,
9845
+ startedAt: Date.now()
9846
+ });
9847
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9848
+ breakId: this.timing.adBreakEpoch,
9849
+ requestId: requestToken,
9850
+ controllerId: this.controllerGeneration
9851
+ });
9852
+ }
9853
+ },
9854
+ {
9855
+ key: "isAdLoadingWithoutPlayback",
9856
+ value: function isAdLoadingWithoutPlayback() {
9857
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9858
+ }
9859
+ },
9860
+ {
9861
+ key: "noteStopBeforeStart",
9862
+ value: function noteStopBeforeStart(reason) {
9863
+ if (!this.isAdLoadingWithoutPlayback()) return;
9864
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9865
+ reason: reason,
9866
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9867
+ });
9868
+ }
9869
+ },
9870
+ {
9871
+ key: "handleRequestWatchdogTimeout",
9872
+ value: function handleRequestWatchdogTimeout() {
9873
+ var adPlayer = this.host.getAdPlayer();
9874
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9875
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9876
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9877
+ });
9878
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9879
+ return;
9880
+ }
9881
+ this.handleAdFailure("request_watchdog_timeout");
8755
9882
  }
8756
9883
  },
8757
9884
  {
8758
- key: "tryNextAvailableAd",
8759
- value: function tryNextAvailableAd() {
8760
- var retryCount = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
9885
+ key: "callController",
9886
+ value: function callController(call) {
8761
9887
  return _async_to_generator(function() {
8762
- var remaining, nextAdUrl, error, errorMessage, maxRetries;
8763
9888
  return _ts_generator(this, function(_state) {
8764
9889
  switch(_state.label){
8765
9890
  case 0:
8766
- if (!this.inAdBreak) {
8767
- return [
8768
- 2
8769
- ];
8770
- }
8771
- remaining = this.timing.getRemainingAdMs();
8772
- if (!this.timing.hasTimeToStartAnotherAd()) {
8773
- if (this.debug) {
8774
- console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(remaining, "ms) to start another ad, ending ad break"));
8775
- }
8776
- this.handleAdPodComplete();
8777
- return [
8778
- 2
8779
- ];
8780
- }
8781
- if (this.timing.isGamInCooldown()) {
8782
- if (this.debug) {
8783
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully");
8784
- }
8785
- this.handleAdPodComplete();
8786
- return [
8787
- 2
8788
- ];
8789
- }
8790
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8791
- if (this.debug) {
8792
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break"));
8793
- }
8794
- this.handleAdPodComplete();
8795
- return [
8796
- 2
8797
- ];
8798
- }
8799
- this.timing.cleanupTemporaryFailures();
9891
+ this.controllerCallInFlight = true;
8800
9892
  _state.label = 1;
8801
9893
  case 1:
8802
- if (!(this.adRequestQueue.length > 0)) return [
8803
- 3,
8804
- 9
8805
- ];
8806
- nextAdUrl = this.adRequestQueue.shift();
8807
- if (!nextAdUrl) return [
8808
- 3,
8809
- 1
8810
- ];
8811
- if (this.timing.failedVastUrls.has(nextAdUrl)) {
8812
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...");
8813
- return [
8814
- 3,
8815
- 1
8816
- ];
8817
- }
8818
- if (this.timing.isUrlInCooldown(nextAdUrl)) {
8819
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...");
8820
- return [
8821
- 3,
8822
- 1
8823
- ];
8824
- }
8825
- if (this.debug) {
8826
- console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex + 1, ", ").concat(this.adRequestQueue.length, " remaining in queue)"));
8827
- }
8828
- _state.label = 2;
8829
- case 2:
8830
9894
  _state.trys.push([
8831
- 2,
8832
- 4,
9895
+ 1,
8833
9896
  ,
8834
- 8
8835
- ]);
8836
- return [
8837
- 4,
8838
- this.playSingleAd(nextAdUrl)
8839
- ];
8840
- case 3:
8841
- _state.sent();
8842
- this.timing.consecutiveFailures = 0;
8843
- return [
8844
- 3,
8845
- 8
8846
- ];
8847
- case 4:
8848
- error = _state.sent();
8849
- errorMessage = error.message;
8850
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad request failed:", errorMessage);
8851
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
8852
9897
  3,
8853
- 6
8854
- ];
8855
- return [
8856
- 4,
8857
- this.tryNextAvailableAdWithRateLimit()
8858
- ];
8859
- case 5:
8860
- _state.sent();
8861
- return [
8862
- 2
8863
- ];
8864
- case 6:
8865
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
8866
- this.timing.consecutiveFailures++;
8867
- }
9898
+ 4
9899
+ ]);
8868
9900
  return [
8869
9901
  4,
8870
- this.tryNextAvailableAdWithRateLimit()
9902
+ call()
8871
9903
  ];
8872
- case 7:
9904
+ case 2:
8873
9905
  _state.sent();
8874
9906
  return [
8875
9907
  3,
8876
- 8
8877
- ];
8878
- case 8:
8879
- return [
8880
- 2
8881
- ];
8882
- case 9:
8883
- maxRetries = 3;
8884
- if (!(this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3)) return [
8885
- 3,
8886
- 12
8887
- ];
8888
- if (this.debug) {
8889
- console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(retryCount + 1, "/").concat(maxRetries, ")"));
8890
- }
8891
- return [
8892
- 4,
8893
- new Promise(function(resolve) {
8894
- return setTimeout(resolve, 500);
8895
- })
8896
- ];
8897
- case 10:
8898
- _state.sent();
8899
- return [
8900
- 4,
8901
- this.tryNextAvailableAd(retryCount + 1)
9908
+ 4
8902
9909
  ];
8903
- case 11:
8904
- _state.sent();
9910
+ case 3:
9911
+ this.controllerCallInFlight = false;
8905
9912
  return [
8906
- 2
9913
+ 7
8907
9914
  ];
8908
- case 12:
8909
- if (!this.isShowingPlaceholder && remaining > 1e3) {
8910
- this.showPlaceholderAndWaitForAds();
8911
- } else {
8912
- if (this.debug) console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break");
8913
- this.handleAdPodComplete();
8914
- }
9915
+ case 4:
8915
9916
  return [
8916
9917
  2
8917
9918
  ];
@@ -8920,47 +9921,33 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8920
9921
  }).call(this);
8921
9922
  }
8922
9923
  },
8923
- {
8924
- // ───────────────────────────────────────────────────────────────
8925
- // Single ad playback
8926
- // ───────────────────────────────────────────────────────────────
8927
- key: "withCurrentPodBudget",
8928
- value: function withCurrentPodBudget(vastTagUrl) {
8929
- var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
8930
- if (!(remaining > 0)) return vastTagUrl;
8931
- try {
8932
- var url = new URL(vastTagUrl);
8933
- if (!url.searchParams.has("pmxd")) return vastTagUrl;
8934
- var maxMs = Math.round(remaining);
8935
- url.searchParams.set("pmxd", String(maxMs));
8936
- var minMs = Number(url.searchParams.get("pmnd"));
8937
- if (Number.isFinite(minMs) && minMs > maxMs) {
8938
- url.searchParams.set("pmnd", String(maxMs));
8939
- }
8940
- return url.toString();
8941
- } catch (unused) {
8942
- return vastTagUrl;
8943
- }
8944
- }
8945
- },
8946
9924
  {
8947
9925
  key: "playSingleAd",
8948
9926
  value: function playSingleAd(vastTagUrl) {
9927
+ var trigger = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "vmap";
8949
9928
  return _async_to_generator(function() {
8950
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
9929
+ var epoch, generation, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, error;
8951
9930
  return _ts_generator(this, function(_state) {
8952
9931
  switch(_state.label){
8953
9932
  case 0:
8954
- adPlayer = this.host.getAdPlayer();
8955
- if (adPlayer.isAdPlaying()) return [
8956
- 2
8957
- ];
9933
+ if (this.slotState === "REQUESTING" || this.slotState === "READY" || this.slotState === "PLAYING" || this.slotState === "ENDING") {
9934
+ this.logOrchestratorFunnel("request_suppressed", {
9935
+ trigger: trigger,
9936
+ state: this.slotState,
9937
+ why: "request_in_flight"
9938
+ });
9939
+ return [
9940
+ 2
9941
+ ];
9942
+ }
8958
9943
  if (this.timing.failedVastUrls.has(vastTagUrl)) {
8959
9944
  if (this.debug) console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:", vastTagUrl);
9945
+ this.timing.consecutiveFailures++;
8960
9946
  throw new Error("VAST URL permanently failed");
8961
9947
  }
8962
9948
  if (this.timing.isUrlInCooldown(vastTagUrl)) {
8963
9949
  if (this.debug) console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):", vastTagUrl);
9950
+ this.timing.consecutiveFailures++;
8964
9951
  throw new Error("VAST URL in cooldown after no-fill");
8965
9952
  }
8966
9953
  if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
@@ -8971,16 +9958,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8971
9958
  if (this.debug) console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request");
8972
9959
  throw new Error("GAM in cooldown");
8973
9960
  }
8974
- this.recreateAdController();
9961
+ epoch = this.timing.adBreakEpoch;
9962
+ this.recreateAdController("new_request");
9963
+ generation = this.controllerGeneration;
8975
9964
  requestToken = ++this.timing.adRequestTokenCounter;
8976
9965
  this.timing.activeAdRequestToken = requestToken;
9966
+ ap = this.host.getAdPlayer();
9967
+ requestUrl = this.withCurrentPodBudget(vastTagUrl);
9968
+ this.currentVastUrl = requestUrl;
9969
+ this.setSlotState("REQUESTING", trigger);
9970
+ this.beginFunnelRequest(ap, requestToken, trigger);
8977
9971
  _state.label = 1;
8978
9972
  case 1:
8979
9973
  _state.trys.push([
8980
9974
  1,
8981
- 8,
9975
+ 5,
8982
9976
  ,
8983
- 9
9977
+ 6
8984
9978
  ]);
8985
9979
  return [
8986
9980
  4,
@@ -8988,265 +9982,87 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8988
9982
  ];
8989
9983
  case 2:
8990
9984
  _state.sent();
9985
+ if (this.isStale(epoch, generation)) return [
9986
+ 2
9987
+ ];
8991
9988
  this.timing.startAdRequestWatchdog(requestToken);
8992
- this.timing.lastAdRequestTime = Date.now();
8993
- ap = this.host.getAdPlayer();
8994
- requestUrl = this.withCurrentPodBudget(vastTagUrl);
8995
- this.currentVastUrl = requestUrl;
8996
9989
  return [
8997
9990
  4,
8998
- ap.requestAds(requestUrl)
9991
+ this.callController(function() {
9992
+ return ap.requestAds(requestUrl);
9993
+ })
8999
9994
  ];
9000
9995
  case 3:
9001
9996
  _state.sent();
9997
+ this.timing.clearAdRequestWatchdog();
9998
+ if (this.isStale(epoch, generation)) {
9999
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
10000
+ requestId: requestToken
10001
+ });
10002
+ return [
10003
+ 2
10004
+ ];
10005
+ }
9002
10006
  sendAdLoadedTracking(this.host.config.licenseKey, {
9003
10007
  source: "hls",
9004
10008
  vastUrl: requestUrl,
9005
10009
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
9006
10010
  }, this.analyticsContext).catch(function() {});
9007
- this.timing.clearAdRequestWatchdog();
9008
- if (this.timing.activeAdRequestToken !== requestToken) return [
9009
- 2
9010
- ];
9011
10011
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
9012
- this.timing.rejectLoadedAdForDuration(ap);
9013
- this.recreateAdController();
10012
+ ;
10013
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
10014
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
10015
+ this.logOrchestratorFunnel("discarded_budget", {
10016
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
10017
+ remainingMs: remainingMs
10018
+ });
9014
10019
  throw new Error("ad_duration_exceeds_budget");
9015
10020
  }
9016
- _state.label = 4;
9017
- case 4:
9018
- _state.trys.push([
9019
- 4,
9020
- 6,
9021
- ,
9022
- 7
9023
- ]);
10021
+ this.setSlotState("READY", "vast_ready");
9024
10022
  this.timing.startAdFailsafeTimer(requestToken);
9025
10023
  return [
9026
10024
  4,
9027
- ap.play()
10025
+ this.callController(function() {
10026
+ return ap.play();
10027
+ })
9028
10028
  ];
9029
- case 5:
10029
+ case 4:
9030
10030
  _state.sent();
9031
- this.timing.markAdStarted();
10031
+ if (this.isStale(epoch, generation)) return [
10032
+ 2
10033
+ ];
9032
10034
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
9033
10035
  this.timing.scheduleAdStopAtBreakBoundary();
9034
10036
  }
9035
10037
  ap.setAdVolume(getAdAudioVolume(ap));
9036
- this.timing.consecutiveFailures = 0;
9037
10038
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9038
10039
  return [
9039
10040
  3,
9040
- 7
9041
- ];
9042
- case 6:
9043
- playError = _state.sent();
9044
- if (this.debug) console.error("[AD-ERROR] Failed to play ad:", playError);
9045
- if (this.timing.isTemporaryAdError(playError)) {
9046
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9047
- if (this.debug) console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown");
9048
- } else {
9049
- this.timing.failedVastUrls.add(vastTagUrl);
9050
- if (this.debug) console.log("[AD-ERROR] Permanent play error - URL blacklisted");
9051
- }
9052
- this.timing.clearAdFailsafeTimer();
9053
- if (this.timing.activeAdRequestToken === requestToken) {
9054
- this.timing.activeAdRequestToken = null;
9055
- }
9056
- throw playError;
9057
- case 7:
9058
- return [
9059
- 3,
9060
- 9
10041
+ 6
9061
10042
  ];
9062
- case 8:
10043
+ case 5:
9063
10044
  error = _state.sent();
9064
- errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "";
9065
- if (this.debug) console.error("[AD-ERROR] Ad request failed:", errorMessage);
9066
- if (this.timing.isTemporaryAdError(error)) {
9067
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9068
- if (this.debug) console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown");
9069
- } else {
9070
- this.timing.failedVastUrls.add(vastTagUrl);
9071
- if (this.debug) console.log("[AD-ERROR] Permanent error - URL blacklisted:", errorMessage);
9072
- }
9073
10045
  this.timing.clearAdRequestWatchdog();
9074
10046
  this.timing.clearAdFailsafeTimer();
9075
10047
  if (this.timing.activeAdRequestToken === requestToken) {
9076
10048
  this.timing.activeAdRequestToken = null;
9077
10049
  }
9078
- throw error;
9079
- case 9:
9080
- return [
9081
- 2
9082
- ];
9083
- }
9084
- });
9085
- }).call(this);
9086
- }
9087
- },
9088
- {
9089
- key: "showPlaceholderAndWaitForAds",
9090
- value: // ───────────────────────────────────────────────────────────────
9091
- // Placeholder wait
9092
- // ───────────────────────────────────────────────────────────────
9093
- function showPlaceholderAndWaitForAds() {
9094
- return _async_to_generator(function() {
9095
- var remaining, waitTime, checkInterval, maxChecks, i, nextAdUrl, error, errorMessage;
9096
- return _ts_generator(this, function(_state) {
9097
- switch(_state.label){
9098
- case 0:
9099
- remaining = this.timing.getRemainingAdMs();
9100
- waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);
9101
- if (this.timing.isGamInCooldown()) {
9102
- if (this.debug) console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait");
9103
- this.handleAdPodComplete();
9104
- return [
9105
- 2
9106
- ];
9107
- }
9108
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9109
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures");
9110
- this.handleAdPodComplete();
9111
- return [
9112
- 2
9113
- ];
9114
- }
9115
- if (waitTime < 1e3) {
9116
- this.handleAdPodComplete();
10050
+ if (this.isStale(epoch, generation)) {
10051
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
10052
+ requestId: requestToken,
10053
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
10054
+ });
9117
10055
  return [
9118
10056
  2
9119
10057
  ];
9120
10058
  }
9121
- if (this.debug) {
9122
- console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(waitTime, "ms while waiting for ad URLs"));
10059
+ if (this.debug) console.error("[AD-ERROR] Ad request failed:", error === null || error === void 0 ? void 0 : error.message);
10060
+ this.recordRequestFailure(error, vastTagUrl);
10061
+ if ((error === null || error === void 0 ? void 0 : error.message) === "ad_duration_exceeds_budget") {
10062
+ this.recreateAdController("discarded_budget");
9123
10063
  }
9124
- this.isShowingPlaceholder = true;
9125
- this.host.getAdPlayer().showPlaceholder();
9126
- checkInterval = 300;
9127
- maxChecks = Math.floor(waitTime / checkInterval);
9128
- i = 0;
9129
- _state.label = 1;
9130
- case 1:
9131
- if (!(i < maxChecks)) return [
9132
- 3,
9133
- 12
9134
- ];
9135
- return [
9136
- 4,
9137
- new Promise(function(resolve) {
9138
- return setTimeout(resolve, checkInterval);
9139
- })
9140
- ];
9141
- case 2:
9142
- _state.sent();
9143
- if (!this.inAdBreak) return [
9144
- 2
9145
- ];
9146
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9147
- if (this.debug) console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait");
9148
- return [
9149
- 3,
9150
- 12
9151
- ];
9152
- }
9153
- if (!this.timing.hasTimeToStartAnotherAd()) {
9154
- if (this.debug) console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break");
9155
- return [
9156
- 3,
9157
- 12
9158
- ];
9159
- }
9160
- _state.label = 3;
9161
- case 3:
9162
- if (!(this.adRequestQueue.length > 0)) return [
9163
- 3,
9164
- 11
9165
- ];
9166
- if (!this.timing.hasTimeToStartAnotherAd()) return [
9167
- 3,
9168
- 11
9169
- ];
9170
- nextAdUrl = this.adRequestQueue.shift();
9171
- if (!nextAdUrl) return [
9172
- 3,
9173
- 3
9174
- ];
9175
- if (this.timing.failedVastUrls.has(nextAdUrl)) return [
9176
- 3,
9177
- 3
9178
- ];
9179
- if (this.timing.isUrlInCooldown(nextAdUrl)) return [
9180
- 3,
9181
- 3
9182
- ];
9183
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player");
9184
- this.isShowingPlaceholder = false;
9185
- this.host.getAdPlayer().hidePlaceholder();
9186
- _state.label = 4;
9187
- case 4:
9188
- _state.trys.push([
9189
- 4,
9190
- 6,
9191
- ,
9192
- 10
9193
- ]);
9194
- return [
9195
- 4,
9196
- this.playSingleAd(nextAdUrl)
9197
- ];
9198
- case 5:
9199
- _state.sent();
9200
- this.timing.consecutiveFailures = 0;
9201
- return [
9202
- 3,
9203
- 10
9204
- ];
10064
+ throw error;
9205
10065
  case 6:
9206
- error = _state.sent();
9207
- errorMessage = error.message;
9208
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
9209
- 3,
9210
- 8
9211
- ];
9212
- return [
9213
- 4,
9214
- this.tryNextAvailableAdWithRateLimit()
9215
- ];
9216
- case 7:
9217
- _state.sent();
9218
- return [
9219
- 2
9220
- ];
9221
- case 8:
9222
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
9223
- this.timing.consecutiveFailures++;
9224
- }
9225
- return [
9226
- 4,
9227
- this.tryNextAvailableAdWithRateLimit()
9228
- ];
9229
- case 9:
9230
- _state.sent();
9231
- return [
9232
- 3,
9233
- 10
9234
- ];
9235
- case 10:
9236
- return [
9237
- 2
9238
- ];
9239
- case 11:
9240
- i++;
9241
- return [
9242
- 3,
9243
- 1
9244
- ];
9245
- case 12:
9246
- if (this.debug) console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break");
9247
- this.isShowingPlaceholder = false;
9248
- this.host.getAdPlayer().hidePlaceholder();
9249
- this.handleAdPodComplete();
9250
10066
  return [
9251
10067
  2
9252
10068
  ];
@@ -9259,26 +10075,136 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9259
10075
  // ───────────────────────────────────────────────────────────────
9260
10076
  // Ad break completion
9261
10077
  // ───────────────────────────────────────────────────────────────
10078
+ key: "logBreakFunnel",
10079
+ value: function logBreakFunnel(endReason) {
10080
+ var funnel = this.breakFunnel;
10081
+ this.breakFunnel = {};
10082
+ if (Object.keys(funnel).length === 0) return;
10083
+ var count = function count(stage) {
10084
+ var _funnel_stage;
10085
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
10086
+ };
10087
+ var countPrefix = function countPrefix(prefix) {
10088
+ return Object.keys(funnel).reduce(function(total, stage) {
10089
+ var _funnel_stage;
10090
+ return stage.indexOf(prefix) === 0 ? total + ((_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0) : total;
10091
+ }, 0);
10092
+ };
10093
+ var breakId = this.opportunityEpoch;
10094
+ var requestRetries = count("gam_http_request_retry");
10095
+ var requests = count("gam_http_request_sent") - requestRetries;
10096
+ if (requests > 0 && count("impression_fired") === 0) {
10097
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
10098
+ breakId: breakId,
10099
+ requests: requests,
10100
+ endReason: endReason
10101
+ });
10102
+ }
10103
+ console.log("[AdBreak][FUNNEL] Break summary", {
10104
+ breakId: breakId,
10105
+ endReason: endReason,
10106
+ opportunities: count("opportunity_created"),
10107
+ vastUrlsGenerated: count("vast_url_generated"),
10108
+ requests: requests,
10109
+ requestRetries: requestRetries,
10110
+ gamResponses: count("gam_response_received"),
10111
+ requestsSuppressed: count("request_suppressed"),
10112
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10113
+ filled: count("vast_received"),
10114
+ noFill: count("no_fill"),
10115
+ fillRejected: count("vast_fill_rejected"),
10116
+ gamAdWithoutImpression: count("gam_ad_without_impression"),
10117
+ playbackFailedAfterFill: count("request_outcome:playback_failed"),
10118
+ requestFailed: count("request_failed"),
10119
+ requestAbortedTimeout: count("request_aborted_timeout"),
10120
+ credentialsRetries: count("vast_credentials_retry"),
10121
+ wrapperFailures: count("wrapper_fetch:failure"),
10122
+ noSupportedMedia: count("vast_no_supported_media"),
10123
+ vpaidOnly: count("vast_no_supported_media:vpaid"),
10124
+ audioOnly: count("vast_no_supported_media:audio_only"),
10125
+ mediaFilesEvaluated: count("mediafile_evaluated"),
10126
+ mediaFilesAccepted: count("mediafile_evaluated:accepted"),
10127
+ controllerDestroys: countPrefix("controller_destroy:"),
10128
+ staleCallbacks: count("stale_callback_ignored") + count("stale_request_result_ignored"),
10129
+ tagAllowsAudio: count("tag_allows_audio"),
10130
+ missingImpression: count("vast_missing_impression"),
10131
+ discardedBudget: count("discarded_budget"),
10132
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10133
+ mediaRejected: count("media_candidate:rejected"),
10134
+ mediaFallbacks: count("media_fallback"),
10135
+ playCalled: count("play_called"),
10136
+ playRejected: count("play_rejected"),
10137
+ mutedRetry: count("muted_retry"),
10138
+ startTimeouts: count("play_resolved_but_never_started"),
10139
+ impressions: count("impression_fired"),
10140
+ impressionUrls: count("impression_urls"),
10141
+ trackingRequests: count("tracking_request_created"),
10142
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10143
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10144
+ trackingInvalidUrls: count("tracking_url_invalid"),
10145
+ vastAdFallbacks: count("vast_ad_fallback"),
10146
+ mediaEvents: count("media_event"),
10147
+ quartile25: count("first_quartile"),
10148
+ quartile50: count("midpoint"),
10149
+ quartile75: count("third_quartile"),
10150
+ complete: count("complete"),
10151
+ stoppedBeforeStart: count("stopped_before_start"),
10152
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10153
+ unexpectedUnmutes: count("unexpected_unmute"),
10154
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10155
+ visibilityHidden: count("while_hidden"),
10156
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10157
+ stages: funnel
10158
+ });
10159
+ }
10160
+ },
10161
+ {
9262
10162
  key: "handleAdPodComplete",
9263
10163
  value: function handleAdPodComplete() {
10164
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "unspecified";
9264
10165
  if (this.debug) {
9265
- console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up");
10166
+ console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up", {
10167
+ reason: reason
10168
+ });
10169
+ }
10170
+ var previousState = this.slotState;
10171
+ var alreadyEnded = previousState === "IDLE" && !this.inAdBreak;
10172
+ this.setSlotState("ENDING", reason);
10173
+ this.cancelScheduledRequest();
10174
+ var adPlayer = this.host.getAdPlayer();
10175
+ if (previousState === "REQUESTING") {
10176
+ var _adPlayer_abortPendingRequest;
10177
+ (_adPlayer_abortPendingRequest = adPlayer.abortPendingRequest) === null || _adPlayer_abortPendingRequest === void 0 ? void 0 : _adPlayer_abortPendingRequest.call(adPlayer, "VAST request aborted: ad break ended (".concat(reason, ")"));
10178
+ }
10179
+ if (!alreadyEnded) {
10180
+ console.log("[AD-CONTROLLER] stop", {
10181
+ controllerId: this.controllerGeneration,
10182
+ requestId: this.currentRequestId,
10183
+ state: previousState,
10184
+ reason: reason
10185
+ });
9266
10186
  }
10187
+ this.finalizeRequestDiagnostics(this.currentRequestId, "break_ended:".concat(reason));
10188
+ this.currentRequestId = void 0;
9267
10189
  this.timing.resetForBreakEnd();
9268
- this.stopContinuousFetching();
10190
+ this.placeholder.hide();
9269
10191
  this.clearPendingAdBreak();
9270
10192
  if (this.isShowingPlaceholder) {
9271
- this.host.getAdPlayer().hidePlaceholder();
10193
+ adPlayer.hidePlaceholder();
9272
10194
  this.isShowingPlaceholder = false;
9273
10195
  }
9274
- this.adRequestQueue = [];
9275
10196
  this.inAdBreak = false;
9276
10197
  this.adDetectSentForCurrentBreak = false;
9277
10198
  this.cueManager.activeScte35BreakKey = void 0;
9278
10199
  this.cueManager.scheduledScte35BreakKey = void 0;
9279
10200
  this.adPodQueue = [];
9280
10201
  this.showAds = false;
9281
- this.host.getAdPlayer().stop().catch(function() {});
10202
+ this.breakSource = void 0;
10203
+ this.followUpBaseVastUrl = void 0;
10204
+ this.unusableResponsesInBreak = 0;
10205
+ adPlayer.stop().catch(function() {});
10206
+ if (!alreadyEnded) this.logBreakFunnel(reason);
10207
+ this.setSlotState("IDLE", "break_complete");
9282
10208
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9283
10209
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9284
10210
  if (this.host.video.muted !== restoredMuted) {
@@ -9572,25 +10498,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9572
10498
  {
9573
10499
  key: "handleAdFailure",
9574
10500
  value: function handleAdFailure() {
9575
- this.timing.consecutiveFailures++;
9576
- this.timing.recordGamNoFill();
9577
- var remaining = this.timing.getRemainingAdMs();
9578
- if (this.debug) {
9579
- console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(remaining, "ms, queued ads=").concat(this.adRequestQueue.length, ", consecutiveFailures=").concat(this.timing.consecutiveFailures), this.adRequestQueue.length > 0 ? {
9580
- queuedUrls: _to_consumable_array(this.adRequestQueue)
9581
- } : {});
9582
- }
9583
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9584
- if (this.debug) console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
9585
- this.handleAdPodComplete();
10501
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "ad_failure";
10502
+ if (!this.inAdBreak) return;
10503
+ if (this.slotState === "REQUESTING" || this.slotState === "ENDING") {
10504
+ this.logOrchestratorFunnel("failure_deferred_to_request", {
10505
+ reason: reason,
10506
+ state: this.slotState
10507
+ });
9586
10508
  return;
9587
10509
  }
9588
- if (this.timing.hasTimeToStartAnotherAd()) {
9589
- this.tryNextAvailableAdWithRateLimit();
9590
- } else {
9591
- if (this.debug) console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:", this.timing.failedVastUrls.size);
9592
- this.handleAdPodComplete();
10510
+ this.timing.consecutiveFailures++;
10511
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
10512
+ if (diag && !diag.failureReason) diag.failureReason = reason;
10513
+ if (this.debug) {
10514
+ console.log("[AdBreak] Ad failure (".concat(reason, "): remaining=").concat(this.timing.getRemainingAdMs(), "ms, consecutiveFailures=").concat(this.timing.consecutiveFailures));
9593
10515
  }
10516
+ this.setSlotState("NEEDS_NEXT_AD", reason);
10517
+ this.requestNextAd(reason);
9594
10518
  }
9595
10519
  }
9596
10520
  ]);
@@ -9630,10 +10554,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9630
10554
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9631
10555
  },
9632
10556
  onWatchdogTimeout: function onWatchdogTimeout() {
9633
- return _this.adBreak.handleAdFailure();
10557
+ return _this.adBreak.handleRequestWatchdogTimeout();
9634
10558
  },
9635
10559
  onFailsafeTimeout: function onFailsafeTimeout() {
9636
- return _this.adBreak.handleAdFailure();
10560
+ return _this.adBreak.handleAdFailure("failsafe_timeout");
9637
10561
  },
9638
10562
  getAdState: function getAdState() {
9639
10563
  return {
@@ -9735,6 +10659,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9735
10659
  licenseKey: this.config.licenseKey
9736
10660
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9737
10661
  mainHlsInstance: this.hlsEngine.hls
10662
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10663
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9738
10664
  } : {}));
9739
10665
  }
9740
10666
  },
@@ -9881,6 +10807,21 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9881
10807
  adBehavior: adBehavior
9882
10808
  });
9883
10809
  }
10810
+ if (this.adBreak.isBreakActive()) {
10811
+ console.log("[AD-CONTROLLER] destroy skipped", {
10812
+ reason: "manifest_parsed_during_break",
10813
+ state: this.adBreak.getSlotState()
10814
+ });
10815
+ return [
10816
+ 2
10817
+ ];
10818
+ }
10819
+ if (this.debug) {
10820
+ console.log("[AD-CONTROLLER] destroy", {
10821
+ reason: "manifest_parsed",
10822
+ state: "IDLE"
10823
+ });
10824
+ }
9884
10825
  this.adPlayer.destroy();
9885
10826
  this.adPlayer = this.createAdPlayer(this.shouldContinueLiveStreamDuringAds());
9886
10827
  this.adPlayer.initialize();
@@ -10062,9 +11003,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10062
11003
  this.timing.setAdBreakDurationBoundary(marker.durationSeconds * 1e3);
10063
11004
  }
10064
11005
  this.timing.scheduleAdStopAtBreakBoundary();
10065
- if (!this.adPlayer.isAdPlaying() && this.timing.activeAdRequestToken === null && this.adBreak.adRequestQueue.length > 0 && this.timing.hasTimeToStartAnotherAd()) {
10066
- this.adBreak.tryNextAvailableAdWithRateLimit();
10067
- }
10068
11006
  return;
10069
11007
  }
10070
11008
  if (marker.type === "end") {
@@ -10076,12 +11014,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10076
11014
  }
10077
11015
  var remaining = this.timing.getRemainingAdMs();
10078
11016
  var adPlaying = this.adPlayer.isAdPlaying();
10079
- var hasQueuedAds = this.adBreak.adRequestQueue.length > 0;
10080
11017
  if (this.debug) {
10081
11018
  console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:", {
10082
11019
  remaining: remaining,
10083
11020
  adPlaying: adPlaying,
10084
- hasQueuedAds: hasQueuedAds,
11021
+ adSlotState: this.adBreak.getSlotState(),
10085
11022
  activeAdRequest: this.timing.activeAdRequestToken !== null
10086
11023
  });
10087
11024
  }
@@ -10089,9 +11026,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10089
11026
  this.timing.clearAdStartTimer();
10090
11027
  this.timing.clearAdStopTimer();
10091
11028
  if (adPlaying) {
11029
+ this.adBreak.noteStopBeforeStart("scte_end");
10092
11030
  this.adPlayer.stop().catch(function() {});
10093
11031
  }
10094
- this.adBreak.handleAdPodComplete();
11032
+ this.adBreak.handleAdPodComplete("scte_end");
10095
11033
  return;
10096
11034
  }
10097
11035
  }
@@ -10099,6 +11037,15 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10099
11037
  {
10100
11038
  key: "startScte35AdBreak",
10101
11039
  value: function startScte35AdBreak(marker, cueKey, durationMs) {
11040
+ if (this.adBreak.isBreakActive()) {
11041
+ if (this.debug) {
11042
+ console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 break start: a break is already active", {
11043
+ state: this.adBreak.getSlotState(),
11044
+ cueKey: cueKey
11045
+ });
11046
+ }
11047
+ return;
11048
+ }
10102
11049
  this.adBreak.inAdBreak = true;
10103
11050
  this.cueManager.activeScte35BreakKey = cueKey !== null && cueKey !== void 0 ? cueKey : this.cueManager.pendingScte35CueKey;
10104
11051
  this.cueManager.scheduledScte35BreakKey = void 0;
@@ -10128,9 +11075,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10128
11075
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10129
11076
  }
10130
11077
  if (adPlaying) {
11078
+ this.adBreak.noteStopBeforeStart("break_boundary");
10131
11079
  this.adPlayer.stop().catch(function() {});
10132
11080
  }
10133
- this.adBreak.handleAdPodComplete();
11081
+ this.adBreak.handleAdPodComplete("break_boundary");
10134
11082
  }
10135
11083
  },
10136
11084
  {
@@ -10140,14 +11088,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10140
11088
  key: "startAdPrefetch",
10141
11089
  value: function startAdPrefetch(marker, fragmentSn, cueKey) {
10142
11090
  if (this.adBreak.pendingAdBreak || this.adBreak.inAdBreak) return;
10143
- var scheduled = this.adConfig.findCurrentOrNextBreak(this.video.currentTime * 1e3);
10144
- var tags = this.adConfig.selectVastTagsForBreak(scheduled);
10145
- var baseVastUrl;
10146
- if (tags && tags.length > 0 && tags[0]) {
10147
- baseVastUrl = tags[0];
10148
- } else if (this.adConfig.apiVastTagUrl) {
10149
- baseVastUrl = this.adConfig.apiVastTagUrl;
10150
- } else {
11091
+ var baseVastUrl = this.adConfig.apiVastTagUrl;
11092
+ if (!baseVastUrl) {
10151
11093
  if (this.debug) console.warn("[StormcloudVideoPlayer] No VAST URL available for prefetch");
10152
11094
  return;
10153
11095
  }
@@ -10177,8 +11119,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10177
11119
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
10178
11120
  }, detectPayload), buildAnalyticsContext(this.config)).catch(function() {});
10179
11121
  if (this.debug) {
10180
- console.log("[PREFETCH] Starting ad prefetch for upcoming ad break");
10181
- console.log("[PREFETCH] Pre-generated pod request URL");
11122
+ console.log("[PREFETCH] Pre-generated pod request URL for upcoming ad break");
10182
11123
  }
10183
11124
  }
10184
11125
  },
@@ -10189,7 +11130,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10189
11130
  key: "onTimeUpdate",
10190
11131
  value: function onTimeUpdate(currentTimeSec) {
10191
11132
  var _this = this;
10192
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11133
+ if (this.adConfig.vmapBreaks.length === 0) return;
10193
11134
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10194
11135
  var nowMs = currentTimeSec * 1e3;
10195
11136
  var breakToPlay = this.adConfig.findBreakForTime(nowMs);
@@ -10206,7 +11147,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10206
11147
  key: "onVideoEnded",
10207
11148
  value: function onVideoEnded() {
10208
11149
  var _this = this;
10209
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11150
+ if (this.adConfig.vmapBreaks.length === 0) return;
10210
11151
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10211
11152
  var durationMs = Number.isFinite(this.video.duration) ? Math.floor(this.video.duration * 1e3) : 0;
10212
11153
  var postroll = this.adConfig.vmapBreaks.find(function(b) {
@@ -10256,6 +11197,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10256
11197
  this.adBreak.showAds = true;
10257
11198
  this.adBreak.inAdBreak = true;
10258
11199
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11200
+ if (durationMs > 0) {
11201
+ this.timing.setAdBreakDurationBoundary(durationMs);
11202
+ }
11203
+ this.adBreak.beginVmapBreak(key);
10259
11204
  _state.label = 1;
10260
11205
  case 1:
10261
11206
  _state.trys.push([
@@ -10266,7 +11211,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10266
11211
  ]);
10267
11212
  return [
10268
11213
  4,
10269
- this.adBreak.playSingleAd(first)
11214
+ this.adBreak.playSingleAd(first, "vmap")
10270
11215
  ];
10271
11216
  case 2:
10272
11217
  _state.sent();
@@ -10279,7 +11224,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10279
11224
  if (this.debug) {
10280
11225
  console.warn("[StormcloudVideoPlayer] VMAP ad request failed:", error);
10281
11226
  }
10282
- this.adBreak.handleAdPodComplete();
11227
+ this.adBreak.continueAfterRequestFailure();
10283
11228
  return [
10284
11229
  3,
10285
11230
  4
@@ -10421,7 +11366,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10421
11366
  key: "destroy",
10422
11367
  value: function destroy() {
10423
11368
  var _this_adPlayer;
10424
- this.adBreak.stopContinuousFetching();
11369
+ this.adBreak.cancelScheduledRequest();
10425
11370
  this.timing.destroy();
10426
11371
  this.adBreak.clearPendingAdBreak();
10427
11372
  this.placeholder.destroy();
@@ -10445,7 +11390,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10445
11390
  this.palNonce.sendPlaybackEnd();
10446
11391
  }
10447
11392
  this.palNonce.reset();
10448
- this.adBreak.adRequestQueue = [];
10449
11393
  this.timing.consecutiveFailures = 0;
10450
11394
  }
10451
11395
  }