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.
@@ -178,6 +178,42 @@ function _object_spread_props(target, source) {
178
178
  }
179
179
  return target;
180
180
  }
181
+ function _object_without_properties(source, excluded) {
182
+ if (source == null) return {};
183
+ var target = {}, sourceKeys, key, i;
184
+ if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
185
+ sourceKeys = Reflect.ownKeys(Object(source));
186
+ for(i = 0; i < sourceKeys.length; i++){
187
+ key = sourceKeys[i];
188
+ if (excluded.indexOf(key) >= 0) continue;
189
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
190
+ target[key] = source[key];
191
+ }
192
+ return target;
193
+ }
194
+ target = _object_without_properties_loose(source, excluded);
195
+ if (Object.getOwnPropertySymbols) {
196
+ sourceKeys = Object.getOwnPropertySymbols(source);
197
+ for(i = 0; i < sourceKeys.length; i++){
198
+ key = sourceKeys[i];
199
+ if (excluded.indexOf(key) >= 0) continue;
200
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
201
+ target[key] = source[key];
202
+ }
203
+ }
204
+ return target;
205
+ }
206
+ function _object_without_properties_loose(source, excluded) {
207
+ if (source == null) return {};
208
+ var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
209
+ for(i = 0; i < sourceKeys.length; i++){
210
+ key = sourceKeys[i];
211
+ if (excluded.indexOf(key) >= 0) continue;
212
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
213
+ target[key] = source[key];
214
+ }
215
+ return target;
216
+ }
181
217
  function _possible_constructor_return(self, call) {
182
218
  if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
183
219
  return _assert_this_initialized(self);
@@ -294,26 +330,6 @@ function _ts_generator(thisArg, body) {
294
330
  };
295
331
  }
296
332
  }
297
- function _ts_values(o) {
298
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
299
- if (m) {
300
- return m.call(o);
301
- }
302
- if (o && typeof o.length === "number") {
303
- return {
304
- next: function() {
305
- if (o && i >= o.length) {
306
- o = void 0;
307
- }
308
- return {
309
- value: o && o[i++],
310
- done: !o
311
- };
312
- }
313
- };
314
- }
315
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
316
- }
317
333
  function _type_of(obj) {
318
334
  "@swc/helpers - typeof";
319
335
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
@@ -774,7 +790,7 @@ function toVastMediaErrorCode(error) {
774
790
  }
775
791
  }
776
792
  function createHlsAdPlayer(contentVideo, options) {
777
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
793
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
778
794
  var adPlaying = false;
779
795
  var originalMutedState = false;
780
796
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -806,6 +822,18 @@ function createHlsAdPlayer(contentVideo, options) {
806
822
  var sawDecodedVideoFrame = false;
807
823
  var videoFrameCallbackHandle;
808
824
  var pendingPlayPromise;
825
+ var currentVastTagUrl;
826
+ var funnelContext = {};
827
+ var mediaProbe;
828
+ var lastPodAdElementCount = 0;
829
+ var mediaCandidates = [];
830
+ var mediaCandidateIndex = 0;
831
+ var mediaStartTimerId;
832
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
833
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
834
+ var pendingVastRequests = /* @__PURE__ */ new Set();
835
+ var pendingRequestAbortReason;
836
+ var forcedMuteByAutoplay = false;
809
837
  function createTrackingState() {
810
838
  return {
811
839
  impression: false,
@@ -856,6 +884,78 @@ function createHlsAdPlayer(contentVideo, options) {
856
884
  }
857
885
  }
858
886
  }
887
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
888
+ "ppid",
889
+ "rdid",
890
+ "idtype",
891
+ "is_lat",
892
+ "ifa",
893
+ "idfa",
894
+ "aaid",
895
+ "uid",
896
+ "user_id",
897
+ "userid",
898
+ "device_id",
899
+ "deviceid",
900
+ "ip",
901
+ "ua",
902
+ "gdpr_consent",
903
+ "us_privacy",
904
+ "gpp",
905
+ "addtl_consent",
906
+ "cust_params",
907
+ "email"
908
+ ]);
909
+ function redactUrl(url) {
910
+ if (!url) return url;
911
+ try {
912
+ var parsed = new URL(url);
913
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
914
+ try {
915
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
916
+ var key = _step.value;
917
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
918
+ parsed.searchParams.set(key, "REDACTED");
919
+ }
920
+ }
921
+ } catch (err) {
922
+ _didIteratorError = true;
923
+ _iteratorError = err;
924
+ } finally{
925
+ try {
926
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
927
+ _iterator.return();
928
+ }
929
+ } finally{
930
+ if (_didIteratorError) {
931
+ throw _iteratorError;
932
+ }
933
+ }
934
+ }
935
+ return parsed.toString();
936
+ } catch (unused) {
937
+ return url.split("?")[0];
938
+ }
939
+ }
940
+ function logFunnel(stage) {
941
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
942
+ var payload = _object_spread({
943
+ stage: stage,
944
+ breakId: funnelContext.breakId,
945
+ requestId: funnelContext.requestId,
946
+ controllerId: funnelContext.controllerId,
947
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
948
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
949
+ podIndex: podIndex,
950
+ podSize: podAds.length,
951
+ vastUrl: redactUrl(currentVastTagUrl),
952
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
953
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
954
+ muted: adVideoElement ? adVideoElement.muted : void 0
955
+ }, extra);
956
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
957
+ emit("ad_funnel", payload);
958
+ }
859
959
  function buildTrackingMacroContext() {
860
960
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
861
961
  var _options2_ad;
@@ -895,20 +995,53 @@ function createHlsAdPlayer(contentVideo, options) {
895
995
  urls.forEach(function(url) {
896
996
  try {
897
997
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
998
+ var trackingHost;
999
+ try {
1000
+ trackingHost = new URL(trackingUrl).host;
1001
+ } catch (unused) {
1002
+ logFunnel("tracking_url_invalid", {
1003
+ trackingUrl: redactUrl(trackingUrl)
1004
+ });
1005
+ return;
1006
+ }
1007
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
1008
+ if (unexpanded) {
1009
+ logFunnel("tracking_url_unexpanded_macro", {
1010
+ trackingHost: trackingHost,
1011
+ macros: Array.from(new Set(unexpanded))
1012
+ });
1013
+ }
898
1014
  var img = new Image(1, 1);
899
1015
  inFlightBeacons.add(img);
900
1016
  var timeoutId;
901
- var release = function release() {
1017
+ var release = function release(outcome) {
902
1018
  if (timeoutId !== void 0) clearTimeout(timeoutId);
903
1019
  img.onload = null;
904
1020
  img.onerror = null;
905
1021
  inFlightBeacons.delete(img);
1022
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
1023
+ if (outcome !== "load") {
1024
+ logFunnel("tracking_request_settled", {
1025
+ reason: outcome,
1026
+ trackingHost: trackingHost
1027
+ });
1028
+ }
906
1029
  };
907
- img.onload = release;
908
- img.onerror = release;
909
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
1030
+ img.onload = function() {
1031
+ return release("load");
1032
+ };
1033
+ img.onerror = function() {
1034
+ return release("error");
1035
+ };
1036
+ timeoutId = setTimeout(function() {
1037
+ return release("timeout");
1038
+ }, BEACON_TIMEOUT_MS);
910
1039
  img.src = trackingUrl;
911
1040
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
1041
+ logFunnel("tracking_request_created", {
1042
+ trackingHost: trackingHost,
1043
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
1044
+ });
912
1045
  } catch (error) {
913
1046
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
914
1047
  }
@@ -938,54 +1071,79 @@ function createHlsAdPlayer(contentVideo, options) {
938
1071
  bitrate: level.bitrate || 5e6
939
1072
  };
940
1073
  }
941
- function selectBestMediaFile(mediaFiles) {
942
- if (mediaFiles.length === 0) {
943
- throw new Error("No media files available");
944
- }
945
- var firstFile = mediaFiles[0];
946
- if (!firstFile) {
947
- throw new Error("No media files available");
948
- }
949
- if (mediaFiles.length === 1) {
950
- return firstFile;
951
- }
1074
+ function getMediaTargetQuality() {
952
1075
  var mainQuality = getMainStreamQuality();
953
- if (!mainQuality) {
954
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
955
- return firstFile;
956
- }
957
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
958
- var scoredFiles = mediaFiles.map(function(file) {
959
- var widthDiff = Math.abs(file.width - mainQuality.width);
960
- var heightDiff = Math.abs(file.height - mainQuality.height);
961
- var resolutionDiff = widthDiff + heightDiff;
962
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
963
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
964
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
965
- return {
1076
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1077
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1078
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1079
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1080
+ return null;
1081
+ }
1082
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1083
+ width: containerWidth,
1084
+ height: containerHeight,
1085
+ bitrate: 5e6
1086
+ };
1087
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1088
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1089
+ return {
1090
+ width: width,
1091
+ height: height,
1092
+ bitrate: base.bitrate
1093
+ };
1094
+ }
1095
+ function rankMediaCandidates(mediaFiles) {
1096
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1097
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1098
+ var target = getMediaTargetQuality();
1099
+ var accepted = [];
1100
+ mediaFiles.forEach(function(file, index) {
1101
+ var isHls = isHlsMediaFile(file);
1102
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1103
+ var canPlay2 = probe.canPlayType(mimeForProbe);
1104
+ var playable = isHls ? import_hls.default.isSupported() || canPlay2 !== "" : canPlay2 !== "";
1105
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1106
+ var details = {
1107
+ index: index,
1108
+ candidateUrl: file.url,
1109
+ candidateType: file.type,
1110
+ width: file.width,
1111
+ height: file.height,
1112
+ bitrate: file.bitrate,
1113
+ canPlayType: canPlay2,
1114
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1115
+ };
1116
+ if (!playable) {
1117
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1118
+ reason: "rejected",
1119
+ why: "cannot_play_type"
1120
+ }));
1121
+ return;
1122
+ }
1123
+ var score = 0;
1124
+ if (target) {
1125
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1126
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1127
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1128
+ }
1129
+ accepted.push({
966
1130
  file: file,
967
1131
  score: score,
968
- resolutionDiff: resolutionDiff,
969
- bitrateDiff: bitrateDiff
970
- };
1132
+ insecure: insecure
1133
+ });
1134
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1135
+ reason: "accepted",
1136
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1137
+ score: score
1138
+ }));
971
1139
  });
972
- scoredFiles.sort(function(a, b) {
1140
+ accepted.sort(function(a, b) {
1141
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
973
1142
  return a.score - b.score;
974
1143
  });
975
- var bestMatch = scoredFiles[0];
976
- if (!bestMatch) {
977
- console.log("[HlsAdPlayer] No best match found, using first media file");
978
- return firstFile;
979
- }
980
- console.log("[HlsAdPlayer] Selected media file:", {
981
- url: bestMatch.file.url,
982
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
983
- bitrate: bestMatch.file.bitrate,
984
- score: bestMatch.score,
985
- resolutionDiff: bestMatch.resolutionDiff,
986
- bitrateDiff: bestMatch.bitrateDiff
1144
+ return accepted.map(function(entry) {
1145
+ return entry.file;
987
1146
  });
988
- return bestMatch.file;
989
1147
  }
990
1148
  function isHlsMediaFile(mediaFile) {
991
1149
  var type = mediaFile.type.toLowerCase();
@@ -1002,59 +1160,181 @@ function createHlsAdPlayer(contentVideo, options) {
1002
1160
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
1003
1161
  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");
1004
1162
  }
1005
- function collectVideoMediaFiles(linear, verbose) {
1163
+ function getMediaProbe() {
1164
+ if (adVideoElement) return adVideoElement;
1165
+ if (!mediaProbe && typeof document !== "undefined") {
1166
+ mediaProbe = document.createElement("video");
1167
+ }
1168
+ return mediaProbe;
1169
+ }
1170
+ function evaluateMediaFile(mf) {
1171
+ var _mf_textContent;
1172
+ var type = mf.getAttribute("type") || "";
1173
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1174
+ var delivery = mf.getAttribute("delivery") || void 0;
1175
+ var codec = mf.getAttribute("codec") || void 0;
1176
+ if (!url) {
1177
+ return {
1178
+ category: "missing_media",
1179
+ whyRejected: "empty_url",
1180
+ canPlayType: ""
1181
+ };
1182
+ }
1183
+ var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1184
+ if (apiFramework === "VPAID") {
1185
+ return {
1186
+ category: "vpaid",
1187
+ whyRejected: "vpaid_not_supported",
1188
+ canPlayType: ""
1189
+ };
1190
+ }
1191
+ try {
1192
+ var protocol = new URL(url).protocol;
1193
+ if (protocol !== "https:" && protocol !== "http:") {
1194
+ return {
1195
+ category: "invalid_url",
1196
+ whyRejected: "protocol_".concat(protocol),
1197
+ canPlayType: ""
1198
+ };
1199
+ }
1200
+ } catch (unused) {
1201
+ return {
1202
+ category: "invalid_url",
1203
+ whyRejected: "unparseable_url",
1204
+ canPlayType: ""
1205
+ };
1206
+ }
1207
+ var bitrateAttr = mf.getAttribute("bitrate");
1208
+ var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1209
+ var file = {
1210
+ url: url,
1211
+ type: type,
1212
+ width: parseInt(mf.getAttribute("width") || "1920", 10),
1213
+ height: parseInt(mf.getAttribute("height") || "1080", 10),
1214
+ bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0,
1215
+ delivery: delivery,
1216
+ codec: codec
1217
+ };
1218
+ if (isAudioMediaFile(file)) {
1219
+ return {
1220
+ category: "audio_only",
1221
+ whyRejected: type.toLowerCase().startsWith("audio/") ? "audio_mime" : "audio_extension",
1222
+ canPlayType: ""
1223
+ };
1224
+ }
1225
+ var isHls = isHlsMediaFile(file);
1226
+ var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1227
+ if (!isHls && hasExplicitDimensions && (file.width <= 1 || file.height <= 1)) {
1228
+ return {
1229
+ category: "audio_only",
1230
+ whyRejected: "zero_dimensions",
1231
+ canPlayType: ""
1232
+ };
1233
+ }
1234
+ var probe = getMediaProbe();
1235
+ if (isHls) {
1236
+ var _ref;
1237
+ var nativeHls = (_ref = probe === null || probe === void 0 ? void 0 : probe.canPlayType("application/vnd.apple.mpegurl")) !== null && _ref !== void 0 ? _ref : "";
1238
+ if (import_hls.default.isSupported()) {
1239
+ return {
1240
+ file: file,
1241
+ whyAccepted: "hls_js",
1242
+ canPlayType: nativeHls
1243
+ };
1244
+ }
1245
+ if (nativeHls !== "") {
1246
+ return {
1247
+ file: file,
1248
+ whyAccepted: "native_hls",
1249
+ canPlayType: nativeHls
1250
+ };
1251
+ }
1252
+ return {
1253
+ category: "unsupported_hls",
1254
+ whyRejected: "no_hls_support",
1255
+ canPlayType: nativeHls
1256
+ };
1257
+ }
1258
+ if (!isProgressiveMediaFile(file)) {
1259
+ return {
1260
+ category: "unsupported_mime",
1261
+ whyRejected: "not_a_video_mime",
1262
+ canPlayType: ""
1263
+ };
1264
+ }
1265
+ if (!probe) {
1266
+ return {
1267
+ file: file,
1268
+ whyAccepted: "no_probe_available",
1269
+ canPlayType: ""
1270
+ };
1271
+ }
1272
+ var baseType = type || "video/mp4";
1273
+ var canPlay2 = probe.canPlayType(baseType);
1274
+ if (canPlay2 === "") {
1275
+ return {
1276
+ category: "unsupported_mime",
1277
+ whyRejected: "canPlayType_empty",
1278
+ canPlayType: canPlay2
1279
+ };
1280
+ }
1281
+ if (codec) {
1282
+ var withCodec = probe.canPlayType("".concat(baseType, '; codecs="').concat(codec, '"'));
1283
+ if (withCodec === "") {
1284
+ return {
1285
+ category: "unsupported_codec",
1286
+ whyRejected: "codec_canPlayType_empty",
1287
+ canPlayType: withCodec
1288
+ };
1289
+ }
1290
+ return {
1291
+ file: file,
1292
+ whyAccepted: "canPlayType_".concat(withCodec),
1293
+ canPlayType: withCodec
1294
+ };
1295
+ }
1296
+ return {
1297
+ file: file,
1298
+ whyAccepted: "canPlayType_".concat(canPlay2),
1299
+ canPlayType: canPlay2
1300
+ };
1301
+ }
1302
+ function collectVideoMediaFiles(linear, verbose, stats) {
1006
1303
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
1007
1304
  var mediaFiles = [];
1305
+ if (stats) stats.total += mediaFileElements.length;
1008
1306
  if (verbose) {
1009
1307
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
1010
1308
  }
1011
1309
  mediaFileElements.forEach(function(mf, index) {
1012
1310
  var _mf_textContent;
1013
- var type = mf.getAttribute("type") || "";
1311
+ var result = evaluateMediaFile(mf);
1014
1312
  var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1015
- var width = mf.getAttribute("width") || "";
1016
- var height = mf.getAttribute("height") || "";
1017
- if (verbose) {
1018
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ': type="').concat(type, '", url="').concat(url, '", width="').concat(width, '", height="').concat(height, '"'));
1019
- }
1020
- if (!url) {
1021
- if (verbose) {
1022
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, " has empty URL"));
1023
- }
1024
- return;
1025
- }
1026
- var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1027
- if (apiFramework === "VPAID") {
1028
- if (verbose) {
1029
- console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
1030
- }
1031
- return;
1032
- }
1033
- var bitrateAttr = mf.getAttribute("bitrate");
1034
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1035
- var mediaFile = {
1036
- url: url,
1037
- type: type,
1038
- width: parseInt(width || "1920", 10),
1039
- height: parseInt(height || "1080", 10),
1040
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
1041
- };
1042
- if (isAudioMediaFile(mediaFile)) {
1043
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1313
+ var accepted = "file" in result;
1314
+ logFunnel("mediafile_evaluated", {
1315
+ reason: accepted ? "accepted" : result.category,
1316
+ index: index,
1317
+ type: mf.getAttribute("type") || "",
1318
+ delivery: mf.getAttribute("delivery") || void 0,
1319
+ codec: mf.getAttribute("codec") || void 0,
1320
+ apiFramework: mf.getAttribute("apiFramework") || void 0,
1321
+ width: mf.getAttribute("width"),
1322
+ height: mf.getAttribute("height"),
1323
+ fileUrl: redactUrl(url),
1324
+ canPlayType: result.canPlayType,
1325
+ whyAccepted: accepted ? result.whyAccepted : void 0,
1326
+ whyRejected: accepted ? void 0 : result.whyRejected
1327
+ });
1328
+ if ("file" in result) {
1329
+ mediaFiles.push(result.file);
1044
1330
  return;
1045
1331
  }
1046
- var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1047
- if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1048
- 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'));
1049
- return;
1332
+ if (stats) {
1333
+ var _stats_categories_result_category;
1334
+ 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;
1050
1335
  }
1051
- if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {
1052
- mediaFiles.push(mediaFile);
1053
- if (verbose) {
1054
- console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1055
- }
1056
- } else if (verbose) {
1057
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1336
+ if (result.category === "audio_only") {
1337
+ 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'));
1058
1338
  }
1059
1339
  });
1060
1340
  return mediaFiles;
@@ -1178,26 +1458,58 @@ function createHlsAdPlayer(contentVideo, options) {
1178
1458
  }
1179
1459
  function parseVastXml(xmlString) {
1180
1460
  try {
1181
- var _adElements_find;
1182
1461
  var xmlDoc = parseXml(xmlString);
1183
1462
  if (!xmlDoc) return {
1184
1463
  type: "empty"
1185
1464
  };
1186
1465
  var root = xmlDoc.documentElement;
1187
1466
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1188
- var adElement = (_adElements_find = adElements.find(function(el) {
1189
- return getAdSequence(el) === void 0;
1190
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1191
- if (!adElement) {
1467
+ if (adElements.length === 0) {
1192
1468
  var _root_getAttribute;
1193
1469
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1194
1470
  return emptyVastResult(root);
1195
1471
  }
1196
- var parsed = parseAdElement(adElement, true);
1197
- if (parsed.type === "wrapper") {
1198
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1472
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1473
+ return getAdSequence(el) === void 0;
1474
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1475
+ return getAdSequence(el) !== void 0;
1476
+ })));
1477
+ var firstEmpty;
1478
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1479
+ try {
1480
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1481
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1482
+ var parsed = parseAdElement(adElement, true);
1483
+ if (parsed.type === "empty") {
1484
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1485
+ continue;
1486
+ }
1487
+ if (index > 0) {
1488
+ logFunnel("vast_ad_fallback", {
1489
+ usedAdIndex: index,
1490
+ adCount: ordered.length
1491
+ });
1492
+ }
1493
+ if (parsed.type === "wrapper") {
1494
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1495
+ }
1496
+ return parsed;
1497
+ }
1498
+ } catch (err) {
1499
+ _didIteratorError = true;
1500
+ _iteratorError = err;
1501
+ } finally{
1502
+ try {
1503
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1504
+ _iterator.return();
1505
+ }
1506
+ } finally{
1507
+ if (_didIteratorError) {
1508
+ throw _iteratorError;
1509
+ }
1510
+ }
1199
1511
  }
1200
- return parsed;
1512
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1201
1513
  } catch (error) {
1202
1514
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1203
1515
  return {
@@ -1243,6 +1555,10 @@ function createHlsAdPlayer(contentVideo, options) {
1243
1555
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1244
1556
  if (adElement.getAttribute("conditionalAd") === "true") {
1245
1557
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1558
+ logFunnel("vast_no_supported_media", {
1559
+ reason: "vpaid",
1560
+ conditionalAd: true
1561
+ });
1246
1562
  return {
1247
1563
  type: "empty",
1248
1564
  errorUrls: errorUrls,
@@ -1251,11 +1567,15 @@ function createHlsAdPlayer(contentVideo, options) {
1251
1567
  }
1252
1568
  var linear;
1253
1569
  var mediaFiles = [];
1570
+ var rejectStats = {
1571
+ total: 0,
1572
+ categories: {}
1573
+ };
1254
1574
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1255
1575
  try {
1256
1576
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1257
1577
  var candidate = _step.value;
1258
- var files = collectVideoMediaFiles(candidate, verbose);
1578
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1259
1579
  if (files.length > 0) {
1260
1580
  linear = candidate;
1261
1581
  mediaFiles = files;
@@ -1278,6 +1598,39 @@ function createHlsAdPlayer(contentVideo, options) {
1278
1598
  }
1279
1599
  if (!linear) {
1280
1600
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1601
+ var reason = "missing_media";
1602
+ var top = 0;
1603
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1604
+ try {
1605
+ for(var _iterator1 = Object.keys(rejectStats.categories)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1606
+ var category = _step1.value;
1607
+ var _rejectStats_categories_category;
1608
+ var count = (_rejectStats_categories_category = rejectStats.categories[category]) !== null && _rejectStats_categories_category !== void 0 ? _rejectStats_categories_category : 0;
1609
+ if (count > top) {
1610
+ top = count;
1611
+ reason = category;
1612
+ }
1613
+ }
1614
+ } catch (err) {
1615
+ _didIteratorError1 = true;
1616
+ _iteratorError1 = err;
1617
+ } finally{
1618
+ try {
1619
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1620
+ _iterator1.return();
1621
+ }
1622
+ } finally{
1623
+ if (_didIteratorError1) {
1624
+ throw _iteratorError1;
1625
+ }
1626
+ }
1627
+ }
1628
+ if (rejectStats.total > 0 && top === 0) reason = "other";
1629
+ logFunnel("vast_no_supported_media", {
1630
+ reason: reason,
1631
+ mediaFileCount: rejectStats.total,
1632
+ rejectedByCategory: rejectStats.categories
1633
+ });
1281
1634
  return {
1282
1635
  type: "empty",
1283
1636
  errorUrls: errorUrls,
@@ -1307,27 +1660,65 @@ function createHlsAdPlayer(contentVideo, options) {
1307
1660
  }
1308
1661
  }
1309
1662
  function fetchVastXml(vastTagUrl) {
1310
- var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include";
1663
+ var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include", kind = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "gam";
1311
1664
  return _async_to_generator(function() {
1312
- var controller, timeoutId, requestVast, response, error, error1;
1665
+ var controller, timeoutId, startedAt, attempt, requestVast, response, error, error1;
1313
1666
  return _ts_generator(this, function(_state) {
1314
1667
  switch(_state.label){
1315
1668
  case 0:
1669
+ if (destroyed) {
1670
+ throw new Error("VAST request skipped: ad player destroyed");
1671
+ }
1316
1672
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1673
+ if (controller) pendingVastRequests.add(controller);
1317
1674
  timeoutId = controller ? setTimeout(function() {
1318
1675
  return controller.abort();
1319
1676
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
1677
+ startedAt = Date.now();
1678
+ attempt = 0;
1320
1679
  requestVast = function requestVast(creds) {
1321
- return fetch(vastTagUrl, _object_spread({
1322
- mode: "cors",
1323
- credentials: creds,
1324
- headers: {
1325
- "Accept": "application/xml, text/xml, */*"
1326
- },
1327
- referrerPolicy: "no-referrer-when-downgrade"
1328
- }, controller ? {
1329
- signal: controller.signal
1330
- } : {}));
1680
+ return _async_to_generator(function() {
1681
+ var response;
1682
+ return _ts_generator(this, function(_state) {
1683
+ switch(_state.label){
1684
+ case 0:
1685
+ attempt++;
1686
+ if (kind === "gam") {
1687
+ logFunnel("gam_http_request_sent", {
1688
+ attempt: attempt,
1689
+ credentials: creds
1690
+ });
1691
+ }
1692
+ return [
1693
+ 4,
1694
+ fetch(vastTagUrl, _object_spread({
1695
+ mode: "cors",
1696
+ credentials: creds,
1697
+ headers: {
1698
+ "Accept": "application/xml, text/xml, */*"
1699
+ },
1700
+ referrerPolicy: "no-referrer-when-downgrade"
1701
+ }, controller ? {
1702
+ signal: controller.signal
1703
+ } : {}))
1704
+ ];
1705
+ case 1:
1706
+ response = _state.sent();
1707
+ if (kind === "gam") {
1708
+ logFunnel("gam_response_received", {
1709
+ attempt: attempt,
1710
+ httpStatus: response.status,
1711
+ ok: response.ok,
1712
+ elapsedMs: Date.now() - startedAt
1713
+ });
1714
+ }
1715
+ return [
1716
+ 2,
1717
+ response
1718
+ ];
1719
+ }
1720
+ });
1721
+ })();
1331
1722
  };
1332
1723
  _state.label = 1;
1333
1724
  case 1:
@@ -1362,6 +1753,9 @@ function createHlsAdPlayer(contentVideo, options) {
1362
1753
  6
1363
1754
  ];
1364
1755
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1756
+ logFunnel("vast_credentials_retry", {
1757
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1758
+ });
1365
1759
  return [
1366
1760
  4,
1367
1761
  requestVast("omit")
@@ -1381,7 +1775,7 @@ function createHlsAdPlayer(contentVideo, options) {
1381
1775
  ];
1382
1776
  case 8:
1383
1777
  if (!response.ok) {
1384
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
1778
+ throw new Error("Failed to fetch VAST: HTTP ".concat(response.status, " ").concat(response.statusText));
1385
1779
  }
1386
1780
  return [
1387
1781
  4,
@@ -1395,11 +1789,15 @@ function createHlsAdPlayer(contentVideo, options) {
1395
1789
  case 10:
1396
1790
  error1 = _state.sent();
1397
1791
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1792
+ if (pendingRequestAbortReason) {
1793
+ throw new Error("".concat(pendingRequestAbortReason, ": ").concat(vastTagUrl));
1794
+ }
1398
1795
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1399
1796
  }
1400
1797
  throw error1;
1401
1798
  case 11:
1402
1799
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1800
+ if (controller) pendingVastRequests.delete(controller);
1403
1801
  return [
1404
1802
  7
1405
1803
  ];
@@ -1413,7 +1811,7 @@ function createHlsAdPlayer(contentVideo, options) {
1413
1811
  }
1414
1812
  function fetchAndParseVastAd(_0) {
1415
1813
  return _async_to_generator(function(vastTagUrl) {
1416
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1814
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1417
1815
  var _arguments = arguments;
1418
1816
  return _ts_generator(this, function(_state) {
1419
1817
  switch(_state.label){
@@ -1421,6 +1819,11 @@ function createHlsAdPlayer(contentVideo, options) {
1421
1819
  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] : {
1422
1820
  followAdditionalWrappers: true
1423
1821
  };
1822
+ if (destroyed) return [
1823
+ 2,
1824
+ null
1825
+ ];
1826
+ fetchStartedAt = Date.now();
1424
1827
  _state.label = 1;
1425
1828
  case 1:
1426
1829
  _state.trys.push([
@@ -1431,7 +1834,7 @@ function createHlsAdPlayer(contentVideo, options) {
1431
1834
  ]);
1432
1835
  return [
1433
1836
  4,
1434
- fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit")
1837
+ fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit", depth === 0 ? "gam" : "wrapper")
1435
1838
  ];
1436
1839
  case 2:
1437
1840
  vastXml = _state.sent();
@@ -1443,14 +1846,35 @@ function createHlsAdPlayer(contentVideo, options) {
1443
1846
  error = _state.sent();
1444
1847
  if (depth === 0) throw error;
1445
1848
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1446
- fireTrackingPixels(accumulatedTracking.error, {
1447
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1849
+ logFunnel("wrapper_fetch", {
1850
+ reason: "failure",
1851
+ depth: depth,
1852
+ wrapperUrl: redactUrl(vastTagUrl),
1853
+ elapsedMs: Date.now() - fetchStartedAt,
1854
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1448
1855
  });
1856
+ if (!destroyed) {
1857
+ fireTrackingPixels(accumulatedTracking.error, {
1858
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1859
+ });
1860
+ }
1449
1861
  return [
1450
1862
  2,
1451
1863
  null
1452
1864
  ];
1453
1865
  case 4:
1866
+ if (destroyed) return [
1867
+ 2,
1868
+ null
1869
+ ];
1870
+ if (depth > 0) {
1871
+ logFunnel("wrapper_fetch", {
1872
+ reason: "success",
1873
+ depth: depth,
1874
+ wrapperUrl: redactUrl(vastTagUrl),
1875
+ elapsedMs: Date.now() - fetchStartedAt
1876
+ });
1877
+ }
1454
1878
  console.log("[HlsAdPlayer] VAST XML received");
1455
1879
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1456
1880
  parsed = parseVastXml(vastXml);
@@ -1482,6 +1906,9 @@ function createHlsAdPlayer(contentVideo, options) {
1482
1906
  ];
1483
1907
  }
1484
1908
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1909
+ logFunnel("inline_resolved", {
1910
+ depth: depth
1911
+ });
1485
1912
  return [
1486
1913
  2,
1487
1914
  parsed.ad
@@ -1492,20 +1919,29 @@ function createHlsAdPlayer(contentVideo, options) {
1492
1919
  }
1493
1920
  function fetchAndParsePod(vastTagUrl) {
1494
1921
  return _async_to_generator(function() {
1495
- 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;
1922
+ 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;
1496
1923
  return _ts_generator(this, function(_state) {
1497
1924
  switch(_state.label){
1498
1925
  case 0:
1926
+ lastPodAdElementCount = 0;
1499
1927
  return [
1500
1928
  4,
1501
1929
  fetchVastXml(vastTagUrl)
1502
1930
  ];
1503
1931
  case 1:
1504
1932
  vastXml = _state.sent();
1933
+ if (destroyed) return [
1934
+ 2,
1935
+ []
1936
+ ];
1505
1937
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1506
1938
  trimmedXml = vastXml.trim();
1507
1939
  if (trimmedXml.length === 0) {
1508
1940
  console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)");
1941
+ logFunnel("vast_parsed", {
1942
+ adElementCount: 0,
1943
+ reason: "empty_body"
1944
+ });
1509
1945
  return [
1510
1946
  2,
1511
1947
  []
@@ -1514,6 +1950,10 @@ function createHlsAdPlayer(contentVideo, options) {
1514
1950
  xmlDoc = parseXml(vastXml);
1515
1951
  if (!xmlDoc) {
1516
1952
  console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1953
+ logFunnel("vast_parsed", {
1954
+ adElementCount: 0,
1955
+ reason: "xml_parse_error"
1956
+ });
1517
1957
  return [
1518
1958
  2,
1519
1959
  []
@@ -1521,10 +1961,21 @@ function createHlsAdPlayer(contentVideo, options) {
1521
1961
  }
1522
1962
  root = xmlDoc.documentElement;
1523
1963
  adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1964
+ logFunnel("vast_parsed", {
1965
+ reason: adElements.length > 0 ? "has_ads" : "no_ads",
1966
+ vastVersion: (_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : void 0,
1967
+ adElementCount: adElements.length,
1968
+ inlineCount: adElements.filter(function(el) {
1969
+ return el.querySelector(":scope > InLine");
1970
+ }).length,
1971
+ wrapperCount: adElements.filter(function(el) {
1972
+ return el.querySelector(":scope > Wrapper");
1973
+ }).length
1974
+ });
1524
1975
  if (adElements.length === 0) {
1525
1976
  ;
1526
1977
  ;
1527
- 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)"));
1978
+ 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)"));
1528
1979
  empty = emptyVastResult(root);
1529
1980
  if (empty.type === "empty" && ((_empty_errorUrls = empty.errorUrls) === null || _empty_errorUrls === void 0 ? void 0 : _empty_errorUrls.length)) {
1530
1981
  ;
@@ -1542,10 +1993,15 @@ function createHlsAdPlayer(contentVideo, options) {
1542
1993
  var _parsed_errorUrls, parsed, _parsed_errorCode;
1543
1994
  return _ts_generator(this, function(_state) {
1544
1995
  parsed = parseAdElement(adElement);
1545
- if (parsed.type === "inline") return [
1546
- 2,
1547
- parsed.ad
1548
- ];
1996
+ if (parsed.type === "inline") {
1997
+ logFunnel("inline_resolved", {
1998
+ depth: 0
1999
+ });
2000
+ return [
2001
+ 2,
2002
+ parsed.ad
2003
+ ];
2004
+ }
1549
2005
  if (parsed.type === "wrapper") {
1550
2006
  return [
1551
2007
  2,
@@ -1723,7 +2179,8 @@ function createHlsAdPlayer(contentVideo, options) {
1723
2179
  7
1724
2180
  ];
1725
2181
  case 21:
1726
- 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"));
2182
+ 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"));
2183
+ lastPodAdElementCount = adElements.length;
1727
2184
  return [
1728
2185
  2,
1729
2186
  ads
@@ -1789,14 +2246,17 @@ function createHlsAdPlayer(contentVideo, options) {
1789
2246
  var progress = currentTime / currentAd.duration;
1790
2247
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1791
2248
  trackingFired.firstQuartile = true;
2249
+ logFunnel("first_quartile");
1792
2250
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1793
2251
  }
1794
2252
  if (progress >= 0.5 && !trackingFired.midpoint) {
1795
2253
  trackingFired.midpoint = true;
2254
+ logFunnel("midpoint");
1796
2255
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1797
2256
  }
1798
2257
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1799
2258
  trackingFired.thirdQuartile = true;
2259
+ logFunnel("third_quartile");
1800
2260
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1801
2261
  }
1802
2262
  };
@@ -1819,6 +2279,16 @@ function createHlsAdPlayer(contentVideo, options) {
1819
2279
  if (!trackingFired.impression) {
1820
2280
  trackingFired.impression = true;
1821
2281
  resolvedAds.add(currentAd);
2282
+ logFunnel("playing", {
2283
+ mutedByAutoplay: forcedMuteByAutoplay,
2284
+ candidateIndex: mediaCandidateIndex
2285
+ });
2286
+ logFunnel("impression_fired", {
2287
+ pixelCount: currentAd.trackingUrls.impression.length
2288
+ });
2289
+ if (currentAd.trackingUrls.impression.length === 0) {
2290
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2291
+ }
1822
2292
  fireTrackingPixels(currentAd.trackingUrls.impression);
1823
2293
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1824
2294
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1841,6 +2311,7 @@ function createHlsAdPlayer(contentVideo, options) {
1841
2311
  sampleViewability();
1842
2312
  settleViewability();
1843
2313
  trackingFired.complete = true;
2314
+ logFunnel("complete");
1844
2315
  fireTrackingPixels(currentAd.trackingUrls.complete);
1845
2316
  console.log("[HlsAdPlayer] Ad completed");
1846
2317
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1849,16 +2320,41 @@ function createHlsAdPlayer(contentVideo, options) {
1849
2320
  handleAdComplete();
1850
2321
  };
1851
2322
  var onError = function onError(e) {
2323
+ var _adVideoElement_error, _adVideoElement_error1;
1852
2324
  if (!adPlaying) return;
1853
2325
  console.error("[HlsAdPlayer] Ad video error:", e);
1854
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1855
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1856
- return;
1857
- }
1858
- handleAdError();
2326
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2327
+ logFunnel("media_error", {
2328
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2329
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2330
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2331
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2332
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2333
+ vastErrorCode: vastErrorCode
2334
+ });
2335
+ recoverFromAdFailure(vastErrorCode);
2336
+ };
2337
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2338
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2339
+ if (!adVideoElement.currentSrc) return;
2340
+ logFunnel("media_event", {
2341
+ reason: event.type,
2342
+ readyState: adVideoElement.readyState,
2343
+ networkState: adVideoElement.networkState,
2344
+ currentSrc: adVideoElement.currentSrc
2345
+ });
1859
2346
  };
1860
2347
  var onVolumeChange = function onVolumeChange() {
1861
2348
  if (!currentAd || !adVideoElement) return;
2349
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2350
+ var userActivation = navigator.userActivation;
2351
+ if (userActivation && !userActivation.isActive) {
2352
+ logFunnel("unexpected_unmute", {
2353
+ paused: adVideoElement.paused
2354
+ });
2355
+ }
2356
+ forcedMuteByAutoplay = false;
2357
+ }
1862
2358
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1863
2359
  if (!trackingFired.start) {
1864
2360
  trackingFired.lastMuted = muted;
@@ -1918,6 +2414,22 @@ function createHlsAdPlayer(contentVideo, options) {
1918
2414
  {
1919
2415
  type: "play",
1920
2416
  handler: onPlay
2417
+ },
2418
+ {
2419
+ type: "stalled",
2420
+ handler: onMediaDiagnostic
2421
+ },
2422
+ {
2423
+ type: "suspend",
2424
+ handler: onMediaDiagnostic
2425
+ },
2426
+ {
2427
+ type: "abort",
2428
+ handler: onMediaDiagnostic
2429
+ },
2430
+ {
2431
+ type: "emptied",
2432
+ handler: onMediaDiagnostic
1921
2433
  }
1922
2434
  ];
1923
2435
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2207,16 +2719,51 @@ function createHlsAdPlayer(contentVideo, options) {
2207
2719
  function settlePendingPlay() {
2208
2720
  pendingPlayPromise = void 0;
2209
2721
  }
2722
+ function toVastPlayErrorCode(error) {
2723
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2724
+ }
2725
+ function failAdPlayback(context, error) {
2726
+ var vastErrorCode = toVastPlayErrorCode(error);
2727
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2728
+ logFunnel("play_failed", {
2729
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2730
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2731
+ vastErrorCode: vastErrorCode
2732
+ });
2733
+ recoverFromAdFailure(vastErrorCode);
2734
+ }
2210
2735
  function startAdPlayback(context) {
2736
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2211
2737
  if (!adVideoElement) return;
2738
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2739
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2740
+ context: context,
2741
+ isConnected: adVideoElement.isConnected,
2742
+ clientWidth: adVideoElement.clientWidth,
2743
+ clientHeight: adVideoElement.clientHeight,
2744
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2745
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2746
+ });
2212
2747
  var playPromise = adVideoElement.play();
2213
2748
  pendingPlayPromise = playPromise;
2214
2749
  playPromise.catch(function(error) {
2215
2750
  if (pendingPlayPromise !== playPromise) {
2216
2751
  return;
2217
2752
  }
2218
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2219
- handleAdError();
2753
+ logFunnel("play_rejected", {
2754
+ context: context,
2755
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2756
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2757
+ });
2758
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2759
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2760
+ originalMutedState = true;
2761
+ forcedMuteByAutoplay = true;
2762
+ adVideoElement.muted = true;
2763
+ startAdPlayback(context, true);
2764
+ return;
2765
+ }
2766
+ failAdPlayback(context, error);
2220
2767
  }).finally(function() {
2221
2768
  if (pendingPlayPromise === playPromise) {
2222
2769
  pendingPlayPromise = void 0;
@@ -2255,25 +2802,120 @@ function createHlsAdPlayer(contentVideo, options) {
2255
2802
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2256
2803
  adVideoElement.muted = originalMutedState;
2257
2804
  }
2805
+ function clearMediaStartTimer() {
2806
+ if (mediaStartTimerId !== void 0) {
2807
+ clearTimeout(mediaStartTimerId);
2808
+ mediaStartTimerId = void 0;
2809
+ }
2810
+ }
2811
+ function startMediaStartTimer() {
2812
+ clearMediaStartTimer();
2813
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2814
+ var startedAt = Date.now();
2815
+ mediaStartTimerId = setTimeout(function() {
2816
+ mediaStartTimerId = void 0;
2817
+ if (!adPlaying || trackingFired.impression) return;
2818
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2819
+ logFunnel("play_resolved_but_never_started", {
2820
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2821
+ elapsedMs: Date.now() - startedAt,
2822
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2823
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2824
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2825
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2826
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2827
+ });
2828
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2829
+ }, MEDIA_START_TIMEOUT_MS);
2830
+ }
2831
+ function resetVideoElementForNextSource() {
2832
+ clearStallWatchdog();
2833
+ if (requiresMediaPipelineResetAfterAds()) {
2834
+ recreateAdVideoElement();
2835
+ setupAdEventListeners();
2836
+ } else {
2837
+ prepareVideoElementForNewSource();
2838
+ }
2839
+ }
2840
+ function tryNextMediaCandidate() {
2841
+ if (!currentAd || trackingFired.impression) return false;
2842
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2843
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2844
+ mediaCandidateIndex++;
2845
+ var next = mediaCandidates[mediaCandidateIndex];
2846
+ if (!next) return false;
2847
+ logFunnel("media_fallback", {
2848
+ failedUrl: failedUrl,
2849
+ nextUrl: next.url,
2850
+ nextType: next.type,
2851
+ candidateIndex: mediaCandidateIndex,
2852
+ candidateCount: mediaCandidates.length
2853
+ });
2854
+ resetVideoElementForNextSource();
2855
+ try {
2856
+ loadMediaCandidate(next);
2857
+ return true;
2858
+ } catch (error) {
2859
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2860
+ return tryNextMediaCandidate();
2861
+ }
2862
+ }
2863
+ function recoverFromAdFailure(vastErrorCode) {
2864
+ clearMediaStartTimer();
2865
+ if (tryNextMediaCandidate()) return;
2866
+ reportCurrentAdError(vastErrorCode);
2867
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2868
+ handleAdError();
2869
+ }
2258
2870
  function loadCurrentAdMedia() {
2259
2871
  if (!adVideoElement || !currentAd) {
2260
2872
  throw new Error("No ad video element or ad to load");
2261
2873
  }
2262
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2874
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2875
+ mediaCandidateIndex = 0;
2876
+ var mediaFile = mediaCandidates[0];
2263
2877
  if (!mediaFile) {
2264
- throw new Error("No media file available for ad");
2878
+ logFunnel("media_unsupported", {
2879
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2880
+ candidates: currentAd.mediaFiles.length
2881
+ });
2882
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2883
+ throw new Error("No media file this browser can play");
2265
2884
  }
2266
- currentAdMediaFile = mediaFile;
2267
- var isHlsAd = isHlsMediaFile(mediaFile);
2268
- console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2269
- if (isHlsAd && import_hls.default.isSupported()) {
2270
- if (adHls) {
2885
+ try {
2886
+ loadMediaCandidate(mediaFile);
2887
+ } catch (error) {
2888
+ if (tryNextMediaCandidate()) return;
2889
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2890
+ throw error;
2891
+ }
2892
+ }
2893
+ function loadMediaCandidate(mediaFile) {
2894
+ if (!adVideoElement || !currentAd) {
2895
+ throw new Error("No ad video element or ad to load");
2896
+ }
2897
+ currentAdMediaFile = mediaFile;
2898
+ var isHlsAd = isHlsMediaFile(mediaFile);
2899
+ logFunnel("media_selected", {
2900
+ width: mediaFile.width,
2901
+ height: mediaFile.height,
2902
+ bitrate: mediaFile.bitrate,
2903
+ candidateIndex: mediaCandidateIndex,
2904
+ candidates: mediaCandidates.length
2905
+ });
2906
+ console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2907
+ startMediaStartTimer();
2908
+ if (isHlsAd && import_hls.default.isSupported()) {
2909
+ if (adHls) {
2271
2910
  adHls.destroy();
2272
2911
  }
2273
2912
  adHls = new import_hls.default({
2274
2913
  enableWorker: true,
2275
2914
  lowLatencyMode: false
2276
2915
  });
2916
+ logFunnel("media_load", {
2917
+ pipeline: "hls.js"
2918
+ });
2277
2919
  adHls.loadSource(mediaFile.url);
2278
2920
  adHls.attachMedia(adVideoElement);
2279
2921
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2283,10 +2925,24 @@ function createHlsAdPlayer(contentVideo, options) {
2283
2925
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2284
2926
  console.error("[HlsAdPlayer] HLS error:", data);
2285
2927
  if (data.fatal) {
2286
- handleAdError();
2928
+ var _data_response, _data_response1, _data_frag;
2929
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2930
+ logFunnel("hls_fatal", {
2931
+ reason: data.details,
2932
+ errorName: data.type,
2933
+ errorMessage: data.details,
2934
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2935
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2936
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2937
+ vastErrorCode: vastErrorCode
2938
+ });
2939
+ recoverFromAdFailure(vastErrorCode);
2287
2940
  }
2288
2941
  });
2289
2942
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2943
+ logFunnel("media_load", {
2944
+ pipeline: "native-hls"
2945
+ });
2290
2946
  adVideoElement.src = mediaFile.url;
2291
2947
  startAdPlayback("native HLS ad playback");
2292
2948
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2294,45 +2950,47 @@ function createHlsAdPlayer(contentVideo, options) {
2294
2950
  adHls.destroy();
2295
2951
  adHls = void 0;
2296
2952
  }
2953
+ logFunnel("media_load", {
2954
+ pipeline: "progressive"
2955
+ });
2297
2956
  adVideoElement.src = mediaFile.url;
2298
2957
  adVideoElement.load();
2299
2958
  startAdPlayback("progressive ad playback");
2300
2959
  } else {
2960
+ clearMediaStartTimer();
2961
+ logFunnel("media_unsupported", {
2962
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2963
+ });
2301
2964
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2302
2965
  }
2303
2966
  }
2304
2967
  function advanceToNextPodAd() {
2305
- if (podIndex >= podAds.length - 1) {
2306
- return false;
2307
- }
2308
- settleViewability();
2309
- podIndex++;
2310
- currentAd = podAds[podIndex];
2311
- currentAdMediaFile = void 0;
2312
- resetAdTracking();
2313
- if (currentAd) {
2314
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2315
- }
2316
- clearStallWatchdog();
2317
- if (requiresMediaPipelineResetAfterAds()) {
2318
- recreateAdVideoElement();
2319
- setupAdEventListeners();
2320
- } else {
2321
- prepareVideoElementForNewSource();
2322
- }
2323
- try {
2324
- loadCurrentAdMedia();
2325
- emit("pod_ad_started", {
2326
- index: podIndex,
2327
- total: podAds.length
2328
- });
2329
- return true;
2330
- } catch (error) {
2331
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2332
- return false;
2968
+ clearMediaStartTimer();
2969
+ while(podIndex < podAds.length - 1){
2970
+ settleViewability();
2971
+ podIndex++;
2972
+ currentAd = podAds[podIndex];
2973
+ currentAdMediaFile = void 0;
2974
+ resetAdTracking();
2975
+ if (currentAd) {
2976
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2977
+ }
2978
+ resetVideoElementForNextSource();
2979
+ try {
2980
+ loadCurrentAdMedia();
2981
+ emit("pod_ad_started", {
2982
+ index: podIndex,
2983
+ total: podAds.length
2984
+ });
2985
+ return true;
2986
+ } catch (error) {
2987
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2988
+ }
2333
2989
  }
2990
+ return false;
2334
2991
  }
2335
2992
  function clearStallWatchdog() {
2993
+ clearMediaStartTimer();
2336
2994
  if (stallWatchdogId != null) {
2337
2995
  clearInterval(stallWatchdogId);
2338
2996
  stallWatchdogId = void 0;
@@ -2348,11 +3006,10 @@ function createHlsAdPlayer(contentVideo, options) {
2348
3006
  function handleAdStall() {
2349
3007
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2350
3008
  clearStallWatchdog();
2351
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2352
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2353
- return;
2354
- }
2355
- handleAdError();
3009
+ logFunnel("stall", {
3010
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
3011
+ });
3012
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2356
3013
  }
2357
3014
  function getDecodedVideoFrameCount(video) {
2358
3015
  try {
@@ -2414,11 +3071,10 @@ function createHlsAdPlayer(contentVideo, options) {
2414
3071
  function handleVideoDecodeFailure() {
2415
3072
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2416
3073
  clearStallWatchdog();
2417
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2418
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2419
- return;
2420
- }
2421
- handleAdError();
3074
+ logFunnel("decode_failure", {
3075
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
3076
+ });
3077
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2422
3078
  }
2423
3079
  function startStallWatchdog() {
2424
3080
  clearStallWatchdog();
@@ -2542,6 +3198,15 @@ function createHlsAdPlayer(contentVideo, options) {
2542
3198
  Promise.reject(new Error("Ad already playing"))
2543
3199
  ];
2544
3200
  }
3201
+ if (destroyed) {
3202
+ return [
3203
+ 2,
3204
+ Promise.reject(new Error("Ad player destroyed"))
3205
+ ];
3206
+ }
3207
+ currentVastTagUrl = vastTagUrl;
3208
+ pendingRequestAbortReason = void 0;
3209
+ logFunnel("request_sent");
2545
3210
  _state.label = 1;
2546
3211
  case 1:
2547
3212
  _state.trys.push([
@@ -2576,8 +3241,29 @@ function createHlsAdPlayer(contentVideo, options) {
2576
3241
  ads = _state.sent();
2577
3242
  _state.label = 4;
2578
3243
  case 4:
3244
+ if (destroyed) {
3245
+ return [
3246
+ 2,
3247
+ Promise.reject(new Error("Ad player destroyed"))
3248
+ ];
3249
+ }
3250
+ if (!ads.length && pendingRequestAbortReason) {
3251
+ throw new Error(pendingRequestAbortReason);
3252
+ }
3253
+ if (!ads.length && lastPodAdElementCount > 0) {
3254
+ console.warn("[HlsAdPlayer] VAST response had ads but none were playable");
3255
+ logFunnel("vast_fill_rejected", {
3256
+ adElementCount: lastPodAdElementCount
3257
+ });
3258
+ emit("ad_error");
3259
+ return [
3260
+ 2,
3261
+ Promise.reject(new Error("VAST fill rejected: no playable ad in response"))
3262
+ ];
3263
+ }
2579
3264
  if (!ads.length) {
2580
3265
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3266
+ logFunnel("no_fill");
2581
3267
  emit("ad_error");
2582
3268
  return [
2583
3269
  2,
@@ -2588,6 +3274,23 @@ function createHlsAdPlayer(contentVideo, options) {
2588
3274
  podIndex = 0;
2589
3275
  currentAd = ads[0];
2590
3276
  currentAdMediaFile = void 0;
3277
+ logFunnel("vast_received", {
3278
+ adCount: ads.length,
3279
+ durations: ads.map(function(ad) {
3280
+ return ad.duration;
3281
+ }),
3282
+ impressionUrls: ads.map(function(ad) {
3283
+ return ad.trackingUrls.impression.length;
3284
+ })
3285
+ });
3286
+ ads.forEach(function(ad, index) {
3287
+ if (ad.trackingUrls.impression.length === 0) {
3288
+ logFunnel("vast_missing_impression", {
3289
+ adIndex: index,
3290
+ missingAdId: ad.id
3291
+ });
3292
+ }
3293
+ });
2591
3294
  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"));
2592
3295
  return [
2593
3296
  2,
@@ -2596,6 +3299,9 @@ function createHlsAdPlayer(contentVideo, options) {
2596
3299
  case 5:
2597
3300
  error = _state.sent();
2598
3301
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3302
+ logFunnel("request_failed", {
3303
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3304
+ });
2599
3305
  emit("ad_error");
2600
3306
  return [
2601
3307
  2,
@@ -2651,13 +3357,22 @@ function createHlsAdPlayer(contentVideo, options) {
2651
3357
  adContainerEl.style.pointerEvents = "auto";
2652
3358
  }
2653
3359
  emit("content_pause");
2654
- loadCurrentAdMedia();
3360
+ try {
3361
+ loadCurrentAdMedia();
3362
+ } catch (loadError) {
3363
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3364
+ throw loadError;
3365
+ }
3366
+ }
2655
3367
  return [
2656
3368
  2,
2657
3369
  Promise.resolve()
2658
3370
  ];
2659
3371
  } catch (error) {
2660
3372
  console.error("[HlsAdPlayer] Error playing ad:", error);
3373
+ logFunnel("play_failed", {
3374
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3375
+ });
2661
3376
  handleAdError();
2662
3377
  return [
2663
3378
  2,
@@ -2699,6 +3414,9 @@ function createHlsAdPlayer(contentVideo, options) {
2699
3414
  var previousMutedState;
2700
3415
  return _ts_generator(this, function(_state) {
2701
3416
  console.log("[HlsAdPlayer] Stopping ad");
3417
+ if (adPlaying && currentAd && !trackingFired.impression) {
3418
+ logFunnel("stopped_before_start");
3419
+ }
2702
3420
  settleViewability();
2703
3421
  fireNotUsedForUnplayedAds();
2704
3422
  clearStallWatchdog();
@@ -2731,15 +3449,18 @@ function createHlsAdPlayer(contentVideo, options) {
2731
3449
  },
2732
3450
  destroy: function destroy() {
2733
3451
  console.log("[HlsAdPlayer] Destroying");
3452
+ if (adPlaying && currentAd && !trackingFired.impression) {
3453
+ logFunnel("stopped_before_start");
3454
+ }
2734
3455
  settleViewability();
2735
3456
  fireNotUsedForUnplayedAds();
2736
3457
  destroyed = true;
2737
- clearStallWatchdog();
3458
+ pendingRequestAbortReason = "Ad player destroyed";
2738
3459
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2739
3460
  try {
2740
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2741
- var timeoutId = _step.value;
2742
- clearTimeout(timeoutId);
3461
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3462
+ var controller = _step.value;
3463
+ controller.abort();
2743
3464
  }
2744
3465
  } catch (err) {
2745
3466
  _didIteratorError = true;
@@ -2755,6 +3476,28 @@ function createHlsAdPlayer(contentVideo, options) {
2755
3476
  }
2756
3477
  }
2757
3478
  }
3479
+ pendingVastRequests.clear();
3480
+ clearStallWatchdog();
3481
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3482
+ try {
3483
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3484
+ var timeoutId = _step1.value;
3485
+ clearTimeout(timeoutId);
3486
+ }
3487
+ } catch (err) {
3488
+ _didIteratorError1 = true;
3489
+ _iteratorError1 = err;
3490
+ } finally{
3491
+ try {
3492
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3493
+ _iterator1.return();
3494
+ }
3495
+ } finally{
3496
+ if (_didIteratorError1) {
3497
+ throw _iteratorError1;
3498
+ }
3499
+ }
3500
+ }
2758
3501
  pendingTimeouts = [];
2759
3502
  adPlaying = false;
2760
3503
  setAdPlayingFlag(false);
@@ -2774,6 +3517,35 @@ function createHlsAdPlayer(contentVideo, options) {
2774
3517
  isAdPlaying: function isAdPlaying() {
2775
3518
  return adPlaying;
2776
3519
  },
3520
+ setFunnelContext: function setFunnelContext(context) {
3521
+ funnelContext = _object_spread({}, context);
3522
+ },
3523
+ abortPendingRequest: function abortPendingRequest() {
3524
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3525
+ if (pendingVastRequests.size === 0) return;
3526
+ pendingRequestAbortReason = reason;
3527
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3528
+ try {
3529
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3530
+ var controller = _step.value;
3531
+ controller.abort();
3532
+ }
3533
+ } catch (err) {
3534
+ _didIteratorError = true;
3535
+ _iteratorError = err;
3536
+ } finally{
3537
+ try {
3538
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3539
+ _iterator.return();
3540
+ }
3541
+ } finally{
3542
+ if (_didIteratorError) {
3543
+ throw _iteratorError;
3544
+ }
3545
+ }
3546
+ }
3547
+ pendingVastRequests.clear();
3548
+ },
2777
3549
  resize: function resize(width, height) {
2778
3550
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2779
3551
  if (adContainerEl) {
@@ -2809,6 +3581,13 @@ function createHlsAdPlayer(contentVideo, options) {
2809
3581
  if (adVideoElement && adPlaying) {
2810
3582
  var clamped = Math.max(0, Math.min(1, volume));
2811
3583
  adVideoElement.volume = clamped;
3584
+ var userActivation = navigator.userActivation;
3585
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3586
+ logFunnel("unmute_blocked_without_gesture", {
3587
+ requestedVolume: clamped
3588
+ });
3589
+ return;
3590
+ }
2812
3591
  adVideoElement.muted = clamped === 0;
2813
3592
  }
2814
3593
  },
@@ -4915,6 +5694,21 @@ function normalizeVastTagUrl(raw) {
4915
5694
  return raw;
4916
5695
  }
4917
5696
  }
5697
+ var GAM_AD_HOSTS = /* @__PURE__ */ new Set([
5698
+ "pubads.g.doubleclick.net",
5699
+ "securepubads.g.doubleclick.net"
5700
+ ]);
5701
+ function ensureVideoAdType(rawUrl) {
5702
+ try {
5703
+ var url = new URL(rawUrl);
5704
+ if (!GAM_AD_HOSTS.has(url.hostname)) return rawUrl;
5705
+ if (url.searchParams.has("ad_type")) return rawUrl;
5706
+ url.searchParams.set("ad_type", "video");
5707
+ return url.toString();
5708
+ } catch (unused) {
5709
+ return rawUrl;
5710
+ }
5711
+ }
4918
5712
  function applyVastMacros(baseUrl, ctx) {
4919
5713
  var expandedUrl = expandInlineMacroPlaceholders(baseUrl, ctx);
4920
5714
  var url;
@@ -6625,7 +7419,7 @@ var AdConfigManager = /*#__PURE__*/ function() {
6625
7419
  } : {}), {
6626
7420
  consent: this.consentSignals
6627
7421
  }));
6628
- var finalUrl = palNonce.injectNonce(urlWithMacros);
7422
+ var finalUrl = palNonce.injectNonce(ensureVideoAdType(urlWithMacros));
6629
7423
  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);
6630
7424
  return finalUrl;
6631
7425
  }
@@ -6872,7 +7666,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6872
7666
  {
6873
7667
  key: "adFitsRemainingBudget",
6874
7668
  value: function adFitsRemainingBudget(durationMs) {
6875
- if (durationMs <= 0) {
7669
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6876
7670
  return true;
6877
7671
  }
6878
7672
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6931,6 +7725,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6931
7725
  value: function markAdStarted() {
6932
7726
  this.currentAdIndex++;
6933
7727
  this.totalAdsInBreak = this.currentAdIndex;
7728
+ }
7729
+ },
7730
+ {
7731
+ key: "noteAdRequestSent",
7732
+ value: function noteAdRequestSent() {
6934
7733
  this.totalAdRequestsInBreak++;
6935
7734
  this.lastAdRequestTime = Date.now();
6936
7735
  }
@@ -6982,6 +7781,9 @@ var AdTimingService = /*#__PURE__*/ function() {
6982
7781
  if (message.includes("timeout")) {
6983
7782
  return true;
6984
7783
  }
7784
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7785
+ return true;
7786
+ }
6985
7787
  if (message.includes("rate limit") || message.includes("too many requests")) {
6986
7788
  return true;
6987
7789
  }
@@ -8106,6 +8908,18 @@ function resizePlayer(video, adPlayer, debug) {
8106
8908
  }
8107
8909
  }
8108
8910
  // src/player/AdBreakOrchestrator.ts
8911
+ var REQUEST_FAILURE_STAGES = /* @__PURE__ */ new Set([
8912
+ "no_fill",
8913
+ "vast_fill_rejected",
8914
+ "request_failed",
8915
+ "media_unsupported",
8916
+ "play_failed",
8917
+ "play_resolved_but_never_started",
8918
+ "hls_fatal",
8919
+ "media_error",
8920
+ "stall",
8921
+ "decode_failure"
8922
+ ]);
8109
8923
  var AdBreakOrchestrator = /*#__PURE__*/ function() {
8110
8924
  function AdBreakOrchestrator(host, timing, adConfig, cueManager, placeholder) {
8111
8925
  _class_call_check(this, AdBreakOrchestrator);
@@ -8113,11 +8927,17 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8113
8927
  this.showAds = false;
8114
8928
  this.isShowingPlaceholder = false;
8115
8929
  this.adDetectSentForCurrentBreak = false;
8116
- this.continuousFetchingActive = false;
8117
- this.continuousFetchLoopRunning = false;
8118
- this.adRequestQueue = [];
8930
+ this.slotState = "IDLE";
8931
+ this.unusableResponsesInBreak = 0;
8932
+ this.controllerGeneration = 0;
8933
+ this.requestDiagnostics = /* @__PURE__ */ new Map();
8934
+ this.breakFunnel = {};
8935
+ this.controllerCallInFlight = false;
8936
+ this.playbackStartedForCurrentRequest = false;
8937
+ this.opportunityEpoch = -1;
8119
8938
  this.adPodQueue = [];
8120
- this.maxPlaceholderDurationMs = 5e3;
8939
+ this.defaultMinRemainingMsToRequestAd = 1e4;
8940
+ this.defaultMaxNoFillsPerBreak = 2;
8121
8941
  this.pendingAdBreak = null;
8122
8942
  this.host = host;
8123
8943
  this.timing = timing;
@@ -8153,7 +8973,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8153
8973
  key: "attachImaEventListeners",
8154
8974
  value: function attachImaEventListeners() {
8155
8975
  var _this = this;
8156
- var adPlayer = this.host.getAdPlayer();
8976
+ var controller = this.host.getAdPlayer();
8977
+ var generation = this.controllerGeneration;
8978
+ var adPlayer = {
8979
+ on: function on(event, handler) {
8980
+ controller.on(event, function(payload) {
8981
+ if (generation !== _this.controllerGeneration) {
8982
+ _this.logOrchestratorFunnel("stale_callback_ignored", {
8983
+ event: event,
8984
+ staleControllerId: generation,
8985
+ currentControllerId: _this.controllerGeneration
8986
+ });
8987
+ return;
8988
+ }
8989
+ handler(payload);
8990
+ });
8991
+ }
8992
+ };
8157
8993
  adPlayer.on("pod_ad_started", function(payload) {
8158
8994
  _this.timing.notePodAdStarted();
8159
8995
  if (_this.debug) {
@@ -8167,7 +9003,35 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8167
9003
  adPlayer.on("ad_interaction", function(event) {
8168
9004
  if (event) _this.host.onAdInteraction(event);
8169
9005
  });
9006
+ adPlayer.on("ad_funnel", function(payload) {
9007
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
9008
+ var stage = payload.stage;
9009
+ _this.countFunnelStage(stage);
9010
+ if (payload.reason) {
9011
+ _this.countFunnelStage("".concat(stage, ":").concat(payload.reason));
9012
+ }
9013
+ if (stage === "impression_fired" && payload.pixelCount != null) {
9014
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
9015
+ }
9016
+ if (payload.visibilityState === "hidden") {
9017
+ _this.countFunnelStage("while_hidden");
9018
+ }
9019
+ if (stage === "gam_http_request_sent") {
9020
+ if (payload.attempt === 1) {
9021
+ _this.timing.noteAdRequestSent();
9022
+ } else {
9023
+ _this.countFunnelStage("gam_http_request_retry");
9024
+ }
9025
+ }
9026
+ _this.recordRequestDiagnostic(payload);
9027
+ });
8170
9028
  adPlayer.on("ad_impression", function() {
9029
+ _this.timing.consecutiveFailures = 0;
9030
+ _this.setSlotState("PLAYING", "impression");
9031
+ if (!_this.playbackStartedForCurrentRequest) {
9032
+ _this.playbackStartedForCurrentRequest = true;
9033
+ _this.timing.markAdStarted();
9034
+ }
8171
9035
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8172
9036
  source: "hls",
8173
9037
  adIndex: _this.timing.currentAdIndex
@@ -8182,16 +9046,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8182
9046
  var remaining = _this.timing.getRemainingAdMs();
8183
9047
  _this.timing.consecutiveFailures = 0;
8184
9048
  if (_this.debug) {
8185
- console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8186
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8187
- } : {});
9049
+ console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms"));
8188
9050
  }
8189
9051
  if (_this.inAdBreak) {
8190
- if (_this.timing.hasTimeToStartAnotherAd()) {
8191
- _this.tryNextAvailableAdWithRateLimit();
8192
- } else {
8193
- _this.handleAdPodComplete();
8194
- }
9052
+ _this.setSlotState("NEEDS_NEXT_AD", "all_ads_completed");
9053
+ _this.requestNextAd("all_ads_completed");
8195
9054
  }
8196
9055
  });
8197
9056
  adPlayer.on("ad_error", function(errorPayload) {
@@ -8211,7 +9070,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8211
9070
  }
8212
9071
  }
8213
9072
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8214
- _this.handleAdFailure();
9073
+ if (_this.controllerCallInFlight) {
9074
+ return;
9075
+ }
9076
+ _this.handleAdFailure("ad_error");
8215
9077
  });
8216
9078
  adPlayer.on("content_pause", function() {
8217
9079
  _this.timing.clearAdFailsafeTimer();
@@ -8250,26 +9112,32 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8250
9112
  }
8251
9113
  _this.timing.consecutiveFailures = 0;
8252
9114
  _this.timing.recordPlayedAdDuration(_this.host.getAdPlayer());
8253
- var remaining = _this.timing.getRemainingAdMs();
8254
9115
  if (_this.debug) {
8255
- console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8256
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8257
- } : {});
8258
- }
8259
- if (_this.timing.hasTimeToStartAnotherAd()) {
8260
- _this.tryNextAvailableAdWithRateLimit();
8261
- } else {
8262
- _this.handleAdPodComplete();
9116
+ console.log("[AdBreak] content_resume: remaining=".concat(_this.timing.getRemainingAdMs(), "ms"));
8263
9117
  }
9118
+ _this.setSlotState("NEEDS_NEXT_AD", "ad_complete");
9119
+ _this.requestNextAd("ad_complete");
8264
9120
  });
8265
9121
  }
8266
9122
  },
8267
9123
  {
8268
9124
  key: "recreateAdController",
8269
- value: function recreateAdController() {
8270
- if (this.debug) {
8271
- console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");
9125
+ value: function recreateAdController(reason) {
9126
+ if (reason === "new_request" && (this.slotState === "REQUESTING" || this.slotState === "READY")) {
9127
+ console.warn("[AD-CONTROLLER] destroy during active request", {
9128
+ controllerId: this.controllerGeneration,
9129
+ requestId: this.currentRequestId,
9130
+ state: this.slotState,
9131
+ reason: reason
9132
+ });
8272
9133
  }
9134
+ console.log("[AD-CONTROLLER] destroy", {
9135
+ controllerId: this.controllerGeneration,
9136
+ requestId: this.currentRequestId,
9137
+ state: this.slotState,
9138
+ reason: reason
9139
+ });
9140
+ this.countFunnelStage("controller_destroy:".concat(reason));
8273
9141
  var shouldShowPlaceholder = this.inAdBreak && this.showAds;
8274
9142
  var adPlayer = this.host.getAdPlayer();
8275
9143
  if (shouldShowPlaceholder && adPlayer) {
@@ -8282,6 +9150,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8282
9150
  }
8283
9151
  var preservedMutedState = adPlayer.getOriginalMutedState();
8284
9152
  var preservedVolumeState = adPlayer.getOriginalVolume();
9153
+ this.playbackStartedForCurrentRequest = false;
8285
9154
  if (adPlayer) {
8286
9155
  try {
8287
9156
  adPlayer.destroy();
@@ -8295,9 +9164,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8295
9164
  var continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();
8296
9165
  var newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);
8297
9166
  this.host.setAdPlayer(newAdPlayer);
9167
+ this.controllerGeneration++;
8298
9168
  newAdPlayer.initialize();
8299
9169
  newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);
8300
9170
  this.attachImaEventListeners();
9171
+ if (this.debug) {
9172
+ console.log("[AD-CONTROLLER] create", {
9173
+ controllerId: this.controllerGeneration,
9174
+ reason: reason
9175
+ });
9176
+ }
8301
9177
  if (shouldShowPlaceholder) {
8302
9178
  this.placeholder.show();
8303
9179
  newAdPlayer.showPlaceholder();
@@ -8318,32 +9194,57 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8318
9194
  }
8319
9195
  },
8320
9196
  {
8321
- key: "handleAdStart",
8322
- value: // ───────────────────────────────────────────────────────────────
9197
+ // ───────────────────────────────────────────────────────────────
8323
9198
  // Ad break start
8324
9199
  // ───────────────────────────────────────────────────────────────
8325
- function handleAdStart(_marker) {
9200
+ key: "isBreakActive",
9201
+ value: function isBreakActive() {
9202
+ return this.slotState !== "IDLE";
9203
+ }
9204
+ },
9205
+ {
9206
+ key: "getSlotState",
9207
+ value: function getSlotState() {
9208
+ return this.slotState;
9209
+ }
9210
+ },
9211
+ {
9212
+ key: "beginVmapBreak",
9213
+ value: function beginVmapBreak(breakKey) {
9214
+ this.breakSource = "vmap";
9215
+ this.followUpBaseVastUrl = void 0;
9216
+ this.unusableResponsesInBreak = 0;
9217
+ this.timing.totalAdRequestsInBreak = 0;
9218
+ this.setSlotState("NEEDS_NEXT_AD", "vmap_break_start");
9219
+ this.noteOpportunity("vmap", breakKey);
9220
+ }
9221
+ },
9222
+ {
9223
+ key: "handleAdStart",
9224
+ value: function handleAdStart(marker) {
8326
9225
  return _async_to_generator(function() {
8327
- var scheduled, tags, baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, podPlayed;
9226
+ var baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, epoch, podPlayed;
8328
9227
  return _ts_generator(this, function(_state) {
8329
9228
  switch(_state.label){
8330
9229
  case 0:
8331
- scheduled = this.adConfig.findCurrentOrNextBreak(this.host.video.currentTime * 1e3);
8332
- if (scheduled) {
8333
- this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));
9230
+ if (this.slotState !== "IDLE") {
9231
+ this.logOrchestratorFunnel("duplicate_break_start", {
9232
+ source: "scte35",
9233
+ state: this.slotState
9234
+ });
9235
+ return [
9236
+ 2
9237
+ ];
8334
9238
  }
8335
- tags = this.adConfig.selectVastTagsForBreak(scheduled);
8336
- if (tags && tags.length > 0 && tags[0]) {
8337
- baseVastUrl = tags[0];
8338
- } else if (this.adConfig.apiVastTagUrl) {
8339
- baseVastUrl = this.adConfig.apiVastTagUrl;
8340
- } else {
9239
+ baseVastUrl = this.adConfig.apiVastTagUrl;
9240
+ if (!baseVastUrl) {
9241
+ console.warn("[AdBreak] SCTE-35 break started but no direct VAST tag is configured");
8341
9242
  this.clearPendingAdBreak();
8342
9243
  return [
8343
9244
  2
8344
9245
  ];
8345
9246
  }
8346
- adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled === null || scheduled === void 0 ? void 0 : scheduled.durationMs;
9247
+ adBreakDurationMs = marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.timing.expectedAdBreakDurationMs;
8347
9248
  if (this.debug) {
8348
9249
  mode = this.host.config.isLiveStream ? "LIVE" : "VOD";
8349
9250
  console.log("[CONTINUOUS-FETCH] ".concat(mode, " MODE: Target duration=").concat(adBreakDurationMs, "ms"));
@@ -8351,9 +9252,12 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8351
9252
  this.timing.failedVastUrls.clear();
8352
9253
  this.timing.temporaryFailureUrls.clear();
8353
9254
  this.timing.consecutiveFailures = 0;
8354
- this.continuousFetchingActive = true;
8355
9255
  this.isShowingPlaceholder = false;
8356
9256
  this.timing.totalAdRequestsInBreak = 0;
9257
+ this.breakSource = "scte35";
9258
+ this.followUpBaseVastUrl = baseVastUrl;
9259
+ this.unusableResponsesInBreak = 0;
9260
+ this.setSlotState("NEEDS_NEXT_AD", "scte35_break_start");
8357
9261
  if (this.adConfig.podAssignedByPrefetch) {
8358
9262
  this.adConfig.podAssignedByPrefetch = false;
8359
9263
  } else {
@@ -8371,29 +9275,18 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8371
9275
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8372
9276
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8373
9277
  }
9278
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
9279
+ epoch = this.timing.adBreakEpoch;
8374
9280
  return [
8375
9281
  4,
8376
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
9282
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8377
9283
  ];
8378
9284
  case 1:
8379
9285
  podPlayed = _state.sent();
8380
- if (!!podPlayed) return [
8381
- 3,
8382
- 3
8383
- ];
8384
- if (this.debug) {
8385
- console.log("[POD] Initial pod request did not fill; attempting top-up pod request");
9286
+ if (!podPlayed && this.inAdBreak && epoch === this.timing.adBreakEpoch) {
9287
+ this.setSlotState("NEEDS_NEXT_AD", "initial_request_failed");
9288
+ this.requestNextAd("initial_request_failed");
8386
9289
  }
8387
- this.continuousFetchingActive = true;
8388
- this.startContinuousFetching(baseVastUrl);
8389
- return [
8390
- 4,
8391
- this.tryNextAvailableAdWithRateLimit()
8392
- ];
8393
- case 2:
8394
- _state.sent();
8395
- _state.label = 3;
8396
- case 3:
8397
9290
  return [
8398
9291
  2
8399
9292
  ];
@@ -8407,12 +9300,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8407
9300
  value: // ───────────────────────────────────────────────────────────────
8408
9301
  // Optimized pod (single multi-ad request)
8409
9302
  // ───────────────────────────────────────────────────────────────
8410
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
9303
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8411
9304
  return _async_to_generator(function() {
8412
- var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
9305
+ var podUrl, prefetched, epoch, generation, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8413
9306
  return _ts_generator(this, function(_state) {
8414
9307
  switch(_state.label){
8415
9308
  case 0:
9309
+ prefetched = !!(this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0);
8416
9310
  if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {
8417
9311
  podUrl = this.pendingAdBreak.vastUrls[0];
8418
9312
  this.clearPendingAdBreak();
@@ -8425,12 +9319,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8425
9319
  false
8426
9320
  ];
8427
9321
  }
8428
- this.continuousFetchingActive = false;
8429
- this.recreateAdController();
9322
+ this.noteVastUrlGenerated(podUrl, prefetched ? "prefetch" : "break_start");
9323
+ epoch = this.timing.adBreakEpoch;
9324
+ this.recreateAdController("new_request");
9325
+ generation = this.controllerGeneration;
8430
9326
  adPlayer = this.host.getAdPlayer();
8431
9327
  requestToken = ++this.timing.adRequestTokenCounter;
8432
9328
  this.timing.activeAdRequestToken = requestToken;
8433
9329
  this.currentVastUrl = podUrl;
9330
+ this.setSlotState("REQUESTING", "initial_pod");
9331
+ this.beginFunnelRequest(adPlayer, requestToken, "initial_pod");
8434
9332
  _state.label = 1;
8435
9333
  case 1:
8436
9334
  _state.trys.push([
@@ -8445,16 +9343,24 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8445
9343
  ];
8446
9344
  case 2:
8447
9345
  _state.sent();
9346
+ if (this.isStale(epoch, generation)) return [
9347
+ 2,
9348
+ true
9349
+ ];
8448
9350
  this.timing.startAdRequestWatchdog(requestToken);
8449
- this.timing.lastAdRequestTime = Date.now();
8450
9351
  return [
8451
9352
  4,
8452
- adPlayer.requestAds(podUrl)
9353
+ this.callController(function() {
9354
+ return adPlayer.requestAds(podUrl);
9355
+ })
8453
9356
  ];
8454
9357
  case 3:
8455
9358
  _state.sent();
8456
9359
  this.timing.clearAdRequestWatchdog();
8457
- if (this.timing.activeAdRequestToken !== requestToken) {
9360
+ if (this.isStale(epoch, generation)) {
9361
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9362
+ requestId: requestToken
9363
+ });
8458
9364
  return [
8459
9365
  2,
8460
9366
  true
@@ -8462,11 +9368,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8462
9368
  }
8463
9369
  podCount = (_ref = (_adPlayer_getPodAdCount = adPlayer.getPodAdCount) === null || _adPlayer_getPodAdCount === void 0 ? void 0 : _adPlayer_getPodAdCount.call(adPlayer)) !== null && _ref !== void 0 ? _ref : 1;
8464
9370
  if (podCount < 1) {
9371
+ if (this.timing.activeAdRequestToken === requestToken) {
9372
+ this.timing.activeAdRequestToken = null;
9373
+ }
9374
+ this.recordRequestFailure(new Error("No ads available"), podUrl);
8465
9375
  return [
8466
9376
  2,
8467
9377
  false
8468
9378
  ];
8469
9379
  }
9380
+ this.setSlotState("READY", "vast_ready");
8470
9381
  if (this.debug) {
8471
9382
  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"));
8472
9383
  }
@@ -8478,18 +9389,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8478
9389
  this.timing.startAdFailsafeTimer(requestToken);
8479
9390
  return [
8480
9391
  4,
8481
- adPlayer.play()
9392
+ this.callController(function() {
9393
+ return adPlayer.play();
9394
+ })
8482
9395
  ];
8483
9396
  case 4:
8484
9397
  _state.sent();
8485
- this.timing.markAdStarted();
9398
+ if (this.isStale(epoch, generation)) return [
9399
+ 2,
9400
+ true
9401
+ ];
8486
9402
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8487
9403
  this.timing.scheduleAdStopAtBreakBoundary();
8488
9404
  }
8489
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8490
- this.timing.consecutiveFailures = 0;
8491
- this.continuousFetchingActive = true;
8492
- this.startContinuousFetching(baseVastUrl);
9405
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8493
9406
  return [
8494
9407
  2,
8495
9408
  true
@@ -8501,14 +9414,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8501
9414
  if (this.timing.activeAdRequestToken === requestToken) {
8502
9415
  this.timing.activeAdRequestToken = null;
8503
9416
  }
9417
+ if (this.isStale(epoch, generation)) {
9418
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9419
+ requestId: requestToken,
9420
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
9421
+ });
9422
+ return [
9423
+ 2,
9424
+ true
9425
+ ];
9426
+ }
8504
9427
  if (this.debug) {
8505
9428
  console.warn("[POD] Optimized pod request/play failed:", error);
8506
9429
  }
8507
- if (this.timing.isTemporaryAdError(error)) {
8508
- this.timing.temporaryFailureUrls.set(podUrl, Date.now());
8509
- }
8510
- this.continuousFetchingActive = true;
8511
- this.recreateAdController();
9430
+ this.recordRequestFailure(error, podUrl);
8512
9431
  return [
8513
9432
  2,
8514
9433
  false
@@ -8524,407 +9443,204 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8524
9443
  },
8525
9444
  {
8526
9445
  // ───────────────────────────────────────────────────────────────
8527
- // Continuous fetching
9446
+ // Next-ad scheduling (single flight)
8528
9447
  // ───────────────────────────────────────────────────────────────
8529
- key: "startContinuousFetching",
8530
- value: function startContinuousFetching(baseVastUrl) {
8531
- if (!this.continuousFetchingActive) {
8532
- return;
8533
- }
8534
- if (this.continuousFetchLoopRunning) {
8535
- if (this.debug) {
8536
- console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start");
8537
- }
8538
- return;
8539
- }
9448
+ key: "setSlotState",
9449
+ value: function setSlotState(next, reason) {
9450
+ if (this.slotState === next) return;
9451
+ var previous = this.slotState;
9452
+ this.slotState = next;
8540
9453
  if (this.debug) {
8541
- console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop");
9454
+ console.log("[AdBreak][STATE] ".concat(previous, " -> ").concat(next), {
9455
+ reason: reason,
9456
+ breakId: this.timing.adBreakEpoch,
9457
+ requestId: this.currentRequestId,
9458
+ controllerId: this.controllerGeneration
9459
+ });
8542
9460
  }
8543
- this.continuousFetchLoopRunning = true;
8544
- this.continuousFetchLoop(baseVastUrl);
8545
9461
  }
8546
9462
  },
8547
9463
  {
8548
- key: "continuousFetchLoop",
8549
- value: function continuousFetchLoop(baseVastUrl) {
8550
- return _async_to_generator(function() {
8551
- var _this, _loop, epoch, _ret;
8552
- return _ts_generator(this, function(_state) {
8553
- switch(_state.label){
8554
- case 0:
8555
- _loop = function() {
8556
- var remaining, maxQueueSize, newAdUrl, queuedUrlsPreview, generationDelay;
8557
- return _ts_generator(this, function(_state) {
8558
- switch(_state.label){
8559
- case 0:
8560
- remaining = Math.min(_this.timing.getWallClockRemainingAdMs(), _this.timing.getDurationBudgetRemainingMs());
8561
- if (remaining <= _this.timing.getMinRemainingMsToStartAd()) {
8562
- if (_this.debug) {
8563
- 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"));
8564
- }
8565
- return [
8566
- 2,
8567
- "break"
8568
- ];
8569
- }
8570
- if (_this.timing.isGamInCooldown()) {
8571
- if (_this.debug) {
8572
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation");
8573
- }
8574
- return [
8575
- 2,
8576
- "break"
8577
- ];
8578
- }
8579
- if (_this.timing.consecutiveFailures >= _this.timing.maxConsecutiveFailures) {
8580
- if (_this.debug) {
8581
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(_this.timing.consecutiveFailures, "), stopping URL generation"));
8582
- }
8583
- return [
8584
- 2,
8585
- "break"
8586
- ];
8587
- }
8588
- if (_this.timing.totalAdRequestsInBreak >= _this.timing.maxTotalAdRequestsPerBreak) {
8589
- if (_this.debug) {
8590
- console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(_this.timing.maxTotalAdRequestsPerBreak, "), stopping"));
8591
- }
8592
- return [
8593
- 2,
8594
- "break"
8595
- ];
8596
- }
8597
- maxQueueSize = 5;
8598
- if (!(_this.adRequestQueue.length >= maxQueueSize)) return [
8599
- 3,
8600
- 2
8601
- ];
8602
- if (_this.debug) {
8603
- console.log("[CONTINUOUS-FETCH] URL queue full (".concat(_this.adRequestQueue.length, "), waiting..."));
8604
- }
8605
- return [
8606
- 4,
8607
- new Promise(function(resolve) {
8608
- return setTimeout(resolve, 1e3);
8609
- })
8610
- ];
8611
- case 1:
8612
- _state.sent();
8613
- return [
8614
- 2,
8615
- "continue"
8616
- ];
8617
- case 2:
8618
- newAdUrl = _this.nextAdRequestUrl(baseVastUrl);
8619
- if (!(!newAdUrl || _this.timing.failedVastUrls.has(newAdUrl) || _this.timing.isUrlInCooldown(newAdUrl))) return [
8620
- 3,
8621
- 4
8622
- ];
8623
- return [
8624
- 4,
8625
- new Promise(function(resolve) {
8626
- return setTimeout(resolve, 500);
8627
- })
8628
- ];
8629
- case 3:
8630
- _state.sent();
8631
- return [
8632
- 2,
8633
- "continue"
8634
- ];
8635
- case 4:
8636
- if (_this.debug) {
8637
- queuedUrlsPreview = _to_consumable_array(_this.adRequestQueue).concat([
8638
- newAdUrl
8639
- ]);
8640
- console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(queuedUrlsPreview.length, ")"), {
8641
- queuedUrls: queuedUrlsPreview
8642
- });
8643
- }
8644
- _this.adRequestQueue.push(newAdUrl);
8645
- generationDelay = _this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, _this.timing.consecutiveFailures), 5e3) : 500;
8646
- return [
8647
- 4,
8648
- new Promise(function(resolve) {
8649
- return setTimeout(resolve, generationDelay);
8650
- })
8651
- ];
8652
- case 5:
8653
- _state.sent();
8654
- return [
8655
- 2
8656
- ];
8657
- }
8658
- });
8659
- };
8660
- epoch = this.timing.adBreakEpoch;
8661
- _state.label = 1;
8662
- case 1:
8663
- if (!(this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch)) return [
8664
- 3,
8665
- 3
8666
- ];
8667
- _this = this;
8668
- return [
8669
- 5,
8670
- _ts_values(_loop())
8671
- ];
8672
- case 2:
8673
- _ret = _state.sent();
8674
- if (_ret === "break") return [
8675
- 3,
8676
- 3
8677
- ];
8678
- return [
8679
- 3,
8680
- 1
8681
- ];
8682
- case 3:
8683
- this.continuousFetchLoopRunning = false;
8684
- if (this.debug) {
8685
- console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length, ")"), this.adRequestQueue.length > 0 ? {
8686
- queuedUrls: _to_consumable_array(this.adRequestQueue)
8687
- } : {});
8688
- }
8689
- return [
8690
- 2
8691
- ];
8692
- }
8693
- });
8694
- }).call(this);
9464
+ key: "isStale",
9465
+ value: function isStale(epoch, generation) {
9466
+ return !this.inAdBreak || epoch !== this.timing.adBreakEpoch || generation !== this.controllerGeneration;
8695
9467
  }
8696
9468
  },
8697
9469
  {
8698
- key: "stopContinuousFetching",
8699
- value: function stopContinuousFetching() {
8700
- this.continuousFetchingActive = false;
8701
- this.continuousFetchLoopRunning = false;
8702
- this.placeholder.hide();
8703
- if (this.debug) {
8704
- console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching");
9470
+ key: "getMinRemainingMsToRequestAd",
9471
+ value: function getMinRemainingMsToRequestAd() {
9472
+ var configured = this.host.config.minRemainingMsToRequestAd;
9473
+ var floor = this.timing.getMinRemainingMsToStartAd();
9474
+ if (typeof configured === "number" && configured >= 0) {
9475
+ return Math.max(configured, floor);
8705
9476
  }
9477
+ return Math.max(this.defaultMinRemainingMsToRequestAd, floor);
8706
9478
  }
8707
9479
  },
8708
9480
  {
8709
- key: "tryNextAvailableAdWithRateLimit",
8710
- value: // ───────────────────────────────────────────────────────────────
8711
- // Ad iteration
8712
- // ───────────────────────────────────────────────────────────────
8713
- function tryNextAvailableAdWithRateLimit() {
8714
- return _async_to_generator(function() {
8715
- var epoch, backoffMultiplier, backoffDelay, effectiveMinInterval, timeSinceLastRequest, waitTime;
8716
- return _ts_generator(this, function(_state) {
8717
- switch(_state.label){
8718
- case 0:
8719
- if (!this.inAdBreak) {
8720
- return [
8721
- 2
8722
- ];
8723
- }
8724
- epoch = this.timing.adBreakEpoch;
8725
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8726
- if (this.debug) {
8727
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
8728
- }
8729
- this.handleAdPodComplete();
8730
- return [
8731
- 2
8732
- ];
8733
- }
8734
- backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);
8735
- backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);
8736
- effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);
8737
- timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;
8738
- if (!(timeSinceLastRequest < effectiveMinInterval)) return [
8739
- 3,
8740
- 2
8741
- ];
8742
- waitTime = effectiveMinInterval - timeSinceLastRequest;
8743
- if (this.debug) {
8744
- console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(waitTime, "ms before next request (backoff: ").concat(this.timing.consecutiveFailures, " failures)"));
8745
- }
8746
- return [
8747
- 4,
8748
- new Promise(function(resolve) {
8749
- return setTimeout(resolve, waitTime);
8750
- })
8751
- ];
8752
- case 1:
8753
- _state.sent();
8754
- _state.label = 2;
8755
- case 2:
8756
- if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {
8757
- return [
8758
- 2
8759
- ];
8760
- }
8761
- return [
8762
- 2,
8763
- this.tryNextAvailableAd(0)
8764
- ];
8765
- }
9481
+ key: "getMaxNoFillsPerBreak",
9482
+ value: function getMaxNoFillsPerBreak() {
9483
+ var configured = this.host.config.maxNoFillsPerBreak;
9484
+ return typeof configured === "number" && configured > 0 ? configured : this.defaultMaxNoFillsPerBreak;
9485
+ }
9486
+ },
9487
+ {
9488
+ key: "isBreakTimeBounded",
9489
+ value: function isBreakTimeBounded() {
9490
+ return this.breakSource === "scte35" || this.timing.expectedAdBreakDurationMs != null;
9491
+ }
9492
+ },
9493
+ {
9494
+ key: "getStopRequestingReason",
9495
+ value: function getStopRequestingReason(remainingMs) {
9496
+ if (this.breakSource === "vmap") {
9497
+ if (this.adPodQueue.length === 0) return "vmap_queue_empty";
9498
+ } else if (this.breakSource !== "scte35" || !this.followUpBaseVastUrl) {
9499
+ return "no_follow_up_source";
9500
+ }
9501
+ if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9502
+ return "max_consecutive_failures";
9503
+ }
9504
+ if (this.unusableResponsesInBreak >= this.getMaxNoFillsPerBreak()) {
9505
+ return "unusable_response_limit";
9506
+ }
9507
+ if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {
9508
+ return "request_cap";
9509
+ }
9510
+ if (this.timing.isGamInCooldown()) {
9511
+ return "gam_cooldown";
9512
+ }
9513
+ if (this.isBreakTimeBounded() && remainingMs < this.getMinRemainingMsToRequestAd()) {
9514
+ return "insufficient_break_time";
9515
+ }
9516
+ return void 0;
9517
+ }
9518
+ },
9519
+ {
9520
+ key: "getNextRequestDelayMs",
9521
+ value: function getNextRequestDelayMs() {
9522
+ var failures = this.timing.consecutiveFailures;
9523
+ var backoff = failures > 0 ? Math.min(this.timing.backoffBaseMs * Math.pow(2, failures), this.timing.maxBackoffMs) : 0;
9524
+ var minInterval = this.timing.minAdRequestIntervalMs + backoff;
9525
+ var sinceLast = Date.now() - this.timing.lastAdRequestTime;
9526
+ return Math.max(0, minInterval - sinceLast);
9527
+ }
9528
+ },
9529
+ {
9530
+ key: "requestNextAd",
9531
+ value: function requestNextAd(trigger) {
9532
+ var _this = this;
9533
+ if (!this.inAdBreak) return;
9534
+ if (this.slotState !== "NEEDS_NEXT_AD") {
9535
+ this.logOrchestratorFunnel("request_suppressed", {
9536
+ trigger: trigger,
9537
+ state: this.slotState,
9538
+ why: "slot_busy"
8766
9539
  });
8767
- }).call(this);
9540
+ return;
9541
+ }
9542
+ if (this.nextAdTimerId != null) {
9543
+ this.logOrchestratorFunnel("request_suppressed", {
9544
+ trigger: trigger,
9545
+ state: this.slotState,
9546
+ why: "request_already_scheduled"
9547
+ });
9548
+ return;
9549
+ }
9550
+ var remainingMs = this.timing.getRemainingAdMs();
9551
+ var stopReason = this.getStopRequestingReason(remainingMs);
9552
+ if (stopReason) {
9553
+ this.logOrchestratorFunnel("next_ad_decision", {
9554
+ trigger: trigger,
9555
+ decision: "end_break",
9556
+ reason: stopReason,
9557
+ remainingMs: remainingMs,
9558
+ requestsSent: this.timing.totalAdRequestsInBreak,
9559
+ unusableResponses: this.unusableResponsesInBreak,
9560
+ consecutiveFailures: this.timing.consecutiveFailures
9561
+ });
9562
+ this.handleAdPodComplete(stopReason);
9563
+ return;
9564
+ }
9565
+ var waitMs = this.getNextRequestDelayMs();
9566
+ if (waitMs > 0 && this.isBreakTimeBounded() && remainingMs - waitMs < this.getMinRemainingMsToRequestAd()) {
9567
+ this.logOrchestratorFunnel("next_ad_decision", {
9568
+ trigger: trigger,
9569
+ decision: "end_break",
9570
+ reason: "insufficient_break_time_after_backoff",
9571
+ remainingMs: remainingMs,
9572
+ waitMs: waitMs
9573
+ });
9574
+ this.handleAdPodComplete("insufficient_break_time_after_backoff");
9575
+ return;
9576
+ }
9577
+ this.logOrchestratorFunnel("next_ad_decision", {
9578
+ trigger: trigger,
9579
+ decision: waitMs > 0 ? "request_after_delay" : "request_now",
9580
+ waitMs: waitMs,
9581
+ remainingMs: remainingMs,
9582
+ consecutiveFailures: this.timing.consecutiveFailures
9583
+ });
9584
+ if (waitMs > 0) {
9585
+ if (!this.isShowingPlaceholder) {
9586
+ this.isShowingPlaceholder = true;
9587
+ this.host.getAdPlayer().showPlaceholder();
9588
+ }
9589
+ var epoch = this.timing.adBreakEpoch;
9590
+ this.nextAdTimerId = window.setTimeout(function() {
9591
+ _this.nextAdTimerId = void 0;
9592
+ if (!_this.inAdBreak || epoch !== _this.timing.adBreakEpoch) return;
9593
+ _this.requestNextAd("".concat(trigger, ":after_delay"));
9594
+ }, waitMs);
9595
+ return;
9596
+ }
9597
+ void this.requestFollowUpAd(trigger);
8768
9598
  }
8769
9599
  },
8770
9600
  {
8771
- key: "tryNextAvailableAd",
8772
- value: function tryNextAvailableAd() {
8773
- var retryCount = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
9601
+ key: "requestFollowUpAd",
9602
+ value: function requestFollowUpAd(trigger) {
8774
9603
  return _async_to_generator(function() {
8775
- var remaining, nextAdUrl, error, errorMessage, maxRetries;
9604
+ var url, epoch, unused;
8776
9605
  return _ts_generator(this, function(_state) {
8777
9606
  switch(_state.label){
8778
9607
  case 0:
8779
- if (!this.inAdBreak) {
8780
- return [
8781
- 2
8782
- ];
8783
- }
8784
- remaining = this.timing.getRemainingAdMs();
8785
- if (!this.timing.hasTimeToStartAnotherAd()) {
8786
- if (this.debug) {
8787
- console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(remaining, "ms) to start another ad, ending ad break"));
8788
- }
8789
- this.handleAdPodComplete();
8790
- return [
8791
- 2
8792
- ];
8793
- }
8794
- if (this.timing.isGamInCooldown()) {
8795
- if (this.debug) {
8796
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully");
8797
- }
8798
- this.handleAdPodComplete();
8799
- return [
8800
- 2
8801
- ];
8802
- }
8803
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8804
- if (this.debug) {
8805
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break"));
8806
- }
8807
- this.handleAdPodComplete();
8808
- return [
8809
- 2
8810
- ];
9608
+ if (this.breakSource === "vmap") {
9609
+ url = this.adPodQueue.shift();
9610
+ } else if (this.followUpBaseVastUrl) {
9611
+ url = this.nextAdRequestUrl(this.followUpBaseVastUrl);
8811
9612
  }
8812
- this.timing.cleanupTemporaryFailures();
9613
+ if (!url) return [
9614
+ 2
9615
+ ];
9616
+ this.noteVastUrlGenerated(ensureVideoAdType(url), trigger);
9617
+ epoch = this.timing.adBreakEpoch;
8813
9618
  _state.label = 1;
8814
9619
  case 1:
8815
- if (!(this.adRequestQueue.length > 0)) return [
8816
- 3,
8817
- 9
8818
- ];
8819
- nextAdUrl = this.adRequestQueue.shift();
8820
- if (!nextAdUrl) return [
8821
- 3,
8822
- 1
8823
- ];
8824
- if (this.timing.failedVastUrls.has(nextAdUrl)) {
8825
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...");
8826
- return [
8827
- 3,
8828
- 1
8829
- ];
8830
- }
8831
- if (this.timing.isUrlInCooldown(nextAdUrl)) {
8832
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...");
8833
- return [
8834
- 3,
8835
- 1
8836
- ];
8837
- }
8838
- if (this.debug) {
8839
- console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex + 1, ", ").concat(this.adRequestQueue.length, " remaining in queue)"));
8840
- }
8841
- _state.label = 2;
8842
- case 2:
8843
9620
  _state.trys.push([
8844
- 2,
8845
- 4,
9621
+ 1,
9622
+ 3,
8846
9623
  ,
8847
- 8
9624
+ 4
8848
9625
  ]);
8849
9626
  return [
8850
9627
  4,
8851
- this.playSingleAd(nextAdUrl)
9628
+ this.playSingleAd(url, trigger)
8852
9629
  ];
8853
- case 3:
8854
- _state.sent();
8855
- this.timing.consecutiveFailures = 0;
8856
- return [
8857
- 3,
8858
- 8
8859
- ];
8860
- case 4:
8861
- error = _state.sent();
8862
- errorMessage = error.message;
8863
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad request failed:", errorMessage);
8864
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
8865
- 3,
8866
- 6
8867
- ];
8868
- return [
8869
- 4,
8870
- this.tryNextAvailableAdWithRateLimit()
8871
- ];
8872
- case 5:
8873
- _state.sent();
8874
- return [
8875
- 2
8876
- ];
8877
- case 6:
8878
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
8879
- this.timing.consecutiveFailures++;
8880
- }
8881
- return [
8882
- 4,
8883
- this.tryNextAvailableAdWithRateLimit()
8884
- ];
8885
- case 7:
9630
+ case 2:
8886
9631
  _state.sent();
8887
9632
  return [
8888
9633
  3,
8889
- 8
9634
+ 4
8890
9635
  ];
8891
- case 8:
9636
+ case 3:
9637
+ unused = _state.sent();
9638
+ this.continueAfterRequestFailure(epoch);
8892
9639
  return [
8893
- 2
8894
- ];
8895
- case 9:
8896
- maxRetries = 3;
8897
- if (!(this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3)) return [
8898
9640
  3,
8899
- 12
8900
- ];
8901
- if (this.debug) {
8902
- console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(retryCount + 1, "/").concat(maxRetries, ")"));
8903
- }
8904
- return [
8905
- 4,
8906
- new Promise(function(resolve) {
8907
- return setTimeout(resolve, 500);
8908
- })
8909
- ];
8910
- case 10:
8911
- _state.sent();
8912
- return [
8913
- 4,
8914
- this.tryNextAvailableAd(retryCount + 1)
8915
- ];
8916
- case 11:
8917
- _state.sent();
8918
- return [
8919
- 2
9641
+ 4
8920
9642
  ];
8921
- case 12:
8922
- if (!this.isShowingPlaceholder && remaining > 1e3) {
8923
- this.showPlaceholderAndWaitForAds();
8924
- } else {
8925
- if (this.debug) console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break");
8926
- this.handleAdPodComplete();
8927
- }
9643
+ case 4:
8928
9644
  return [
8929
9645
  2
8930
9646
  ];
@@ -8933,12 +9649,168 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8933
9649
  }).call(this);
8934
9650
  }
8935
9651
  },
9652
+ {
9653
+ key: "continueAfterRequestFailure",
9654
+ value: function continueAfterRequestFailure() {
9655
+ var epoch = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.timing.adBreakEpoch;
9656
+ if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) return;
9657
+ this.setSlotState("NEEDS_NEXT_AD", "request_failed");
9658
+ this.requestNextAd("after_failure");
9659
+ }
9660
+ },
9661
+ {
9662
+ key: "cancelScheduledRequest",
9663
+ value: function cancelScheduledRequest() {
9664
+ if (this.nextAdTimerId != null) {
9665
+ clearTimeout(this.nextAdTimerId);
9666
+ this.nextAdTimerId = void 0;
9667
+ }
9668
+ }
9669
+ },
9670
+ {
9671
+ key: "noteVastUrlGenerated",
9672
+ value: function noteVastUrlGenerated(url, source) {
9673
+ var _ref, _ref1, _ref2, _ref3, _ref4;
9674
+ var params;
9675
+ try {
9676
+ params = new URL(url).searchParams;
9677
+ } catch (unused) {}
9678
+ var adType = (_ref = params === null || params === void 0 ? void 0 : params.get("ad_type")) !== null && _ref !== void 0 ? _ref : void 0;
9679
+ this.logOrchestratorFunnel("vast_url_generated", {
9680
+ source: source,
9681
+ pod: (_ref1 = params === null || params === void 0 ? void 0 : params.get("pod")) !== null && _ref1 !== void 0 ? _ref1 : void 0,
9682
+ pmad: (_ref2 = params === null || params === void 0 ? void 0 : params.get("pmad")) !== null && _ref2 !== void 0 ? _ref2 : void 0,
9683
+ pmnd: (_ref3 = params === null || params === void 0 ? void 0 : params.get("pmnd")) !== null && _ref3 !== void 0 ? _ref3 : void 0,
9684
+ pmxd: (_ref4 = params === null || params === void 0 ? void 0 : params.get("pmxd")) !== null && _ref4 !== void 0 ? _ref4 : void 0,
9685
+ adType: adType
9686
+ });
9687
+ if (adType === "audio" || adType === "audio_video") {
9688
+ console.warn("[AdBreak] VAST tag requests ad_type=".concat(adType, "; GAM may return audio-only creatives, which this video player rejects"));
9689
+ this.countFunnelStage("tag_allows_audio");
9690
+ }
9691
+ }
9692
+ },
9693
+ {
9694
+ key: "recordRequestFailure",
9695
+ value: function recordRequestFailure(error, vastTagUrl) {
9696
+ var _diag_vastAdCount;
9697
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
9698
+ var message = (error === null || error === void 0 ? void 0 : error.message) || "";
9699
+ var outcome;
9700
+ if (message.includes("ad_duration_exceeds_budget")) {
9701
+ outcome = "discarded_budget";
9702
+ } else if (message.includes("VAST fill rejected")) {
9703
+ outcome = "fill_rejected";
9704
+ } else if (/no ads available|no fill|nofill/i.test(message)) {
9705
+ outcome = "no_fill";
9706
+ } else if (/timeout/i.test(message)) {
9707
+ outcome = "request_timeout";
9708
+ } else if (/destroyed|aborted/i.test(message)) {
9709
+ outcome = "request_aborted";
9710
+ } else if (diag && ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired) {
9711
+ outcome = "playback_failed";
9712
+ } else {
9713
+ outcome = "request_failed";
9714
+ }
9715
+ this.timing.consecutiveFailures++;
9716
+ if (outcome === "no_fill" || outcome === "fill_rejected" || outcome === "discarded_budget") {
9717
+ this.unusableResponsesInBreak++;
9718
+ }
9719
+ if (outcome === "no_fill") {
9720
+ this.timing.recordGamNoFill();
9721
+ }
9722
+ if (diag && !diag.failureReason) {
9723
+ diag.failureReason = "".concat(outcome, ": ").concat(message);
9724
+ }
9725
+ if (this.timing.isTemporaryAdError(error)) {
9726
+ this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9727
+ } else if (outcome !== "discarded_budget") {
9728
+ this.timing.failedVastUrls.add(vastTagUrl);
9729
+ }
9730
+ this.countFunnelStage("request_outcome:".concat(outcome));
9731
+ this.logOrchestratorFunnel("request_outcome", {
9732
+ outcome: outcome,
9733
+ errorMessage: message,
9734
+ consecutiveFailures: this.timing.consecutiveFailures,
9735
+ unusableResponsesInBreak: this.unusableResponsesInBreak
9736
+ });
9737
+ }
9738
+ },
9739
+ {
9740
+ // ───────────────────────────────────────────────────────────────
9741
+ // Per-request diagnostics
9742
+ // ───────────────────────────────────────────────────────────────
9743
+ key: "recordRequestDiagnostic",
9744
+ value: function recordRequestDiagnostic(payload) {
9745
+ var requestId = payload.requestId;
9746
+ if (typeof requestId !== "number") return;
9747
+ var diag = this.requestDiagnostics.get(requestId);
9748
+ if (!diag) return;
9749
+ switch(payload.stage){
9750
+ case "gam_http_request_sent":
9751
+ diag.gamRequestSent++;
9752
+ break;
9753
+ case "gam_response_received":
9754
+ diag.vastHttpStatus = payload.httpStatus;
9755
+ break;
9756
+ case "vast_parsed":
9757
+ diag.vastAdCount = payload.adElementCount;
9758
+ break;
9759
+ case "wrapper_fetch":
9760
+ case "inline_resolved":
9761
+ if (typeof payload.depth === "number") {
9762
+ diag.wrapperDepth = Math.max(diag.wrapperDepth, payload.depth);
9763
+ }
9764
+ if (payload.stage === "inline_resolved") diag.inlineResolved = true;
9765
+ break;
9766
+ case "mediafile_evaluated":
9767
+ diag.mediaCandidateCount++;
9768
+ if (payload.whyAccepted) diag.supportedMediaCount++;
9769
+ break;
9770
+ case "playing":
9771
+ diag.playStarted = true;
9772
+ break;
9773
+ case "impression_fired":
9774
+ diag.impressionFired = true;
9775
+ break;
9776
+ default:
9777
+ if (REQUEST_FAILURE_STAGES.has(payload.stage) && !diag.failureReason) {
9778
+ diag.failureReason = payload.reason ? "".concat(payload.stage, ":").concat(payload.reason) : payload.stage;
9779
+ }
9780
+ }
9781
+ }
9782
+ },
9783
+ {
9784
+ key: "finalizeRequestDiagnostics",
9785
+ value: function finalizeRequestDiagnostics(requestId, endReason) {
9786
+ var _diag_vastAdCount;
9787
+ if (requestId == null) return;
9788
+ var diag = this.requestDiagnostics.get(requestId);
9789
+ if (!diag) return;
9790
+ this.requestDiagnostics.delete(requestId);
9791
+ if (!diag.impressionFired && !diag.failureReason && endReason) {
9792
+ diag.failureReason = endReason;
9793
+ }
9794
+ var gamReturnedAdWithoutImpression = ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired;
9795
+ if (gamReturnedAdWithoutImpression) {
9796
+ this.countFunnelStage("gam_ad_without_impression");
9797
+ }
9798
+ var startedAt = diag.startedAt, fields = _object_without_properties(diag, [
9799
+ "startedAt"
9800
+ ]);
9801
+ console.log("[AdBreak][REQUEST] summary", _object_spread_props(_object_spread({}, fields), {
9802
+ durationMs: Date.now() - startedAt,
9803
+ gamReturnedAdWithoutImpression: gamReturnedAdWithoutImpression
9804
+ }));
9805
+ }
9806
+ },
8936
9807
  {
8937
9808
  // ───────────────────────────────────────────────────────────────
8938
9809
  // Single ad playback
8939
9810
  // ───────────────────────────────────────────────────────────────
8940
9811
  key: "withCurrentPodBudget",
8941
- value: function withCurrentPodBudget(vastTagUrl) {
9812
+ value: function withCurrentPodBudget(rawVastTagUrl) {
9813
+ var vastTagUrl = ensureVideoAdType(rawVastTagUrl);
8942
9814
  var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
8943
9815
  if (!(remaining > 0)) return vastTagUrl;
8944
9816
  try {
@@ -8957,23 +9829,174 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8957
9829
  }
8958
9830
  },
8959
9831
  {
8960
- key: "playSingleAd",
8961
- value: function playSingleAd(vastTagUrl) {
9832
+ key: "countFunnelStage",
9833
+ value: function countFunnelStage(stage) {
9834
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9835
+ var _this_breakFunnel_stage;
9836
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9837
+ }
9838
+ },
9839
+ {
9840
+ key: "logOrchestratorFunnel",
9841
+ value: function logOrchestratorFunnel(stage) {
9842
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9843
+ this.countFunnelStage(stage);
9844
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9845
+ breakId: this.timing.adBreakEpoch,
9846
+ requestId: this.currentRequestId,
9847
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9848
+ }, extra));
9849
+ }
9850
+ },
9851
+ {
9852
+ key: "noteOpportunity",
9853
+ value: function noteOpportunity(source, breakKey) {
9854
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9855
+ this.logOrchestratorFunnel("duplicate_break_start", {
9856
+ source: source,
9857
+ breakKey: breakKey
9858
+ });
9859
+ return;
9860
+ }
9861
+ this.opportunityBreakKey = breakKey;
9862
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9863
+ this.logOrchestratorFunnel("opportunity_created", {
9864
+ source: source,
9865
+ breakKey: breakKey,
9866
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9867
+ });
9868
+ }
9869
+ },
9870
+ {
9871
+ key: "beginFunnelRequest",
9872
+ value: function beginFunnelRequest(adPlayer, requestToken, trigger) {
9873
+ var _adPlayer_setFunnelContext;
9874
+ if (this.controllerCallInFlight) {
9875
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9876
+ newRequestId: requestToken
9877
+ });
9878
+ }
9879
+ this.finalizeRequestDiagnostics(this.currentRequestId);
9880
+ this.currentRequestId = requestToken;
9881
+ this.requestStartedAt = Date.now();
9882
+ this.requestDiagnostics.set(requestToken, {
9883
+ breakId: this.timing.adBreakEpoch,
9884
+ requestId: requestToken,
9885
+ controllerId: this.controllerGeneration,
9886
+ trigger: trigger,
9887
+ gamRequestSent: 0,
9888
+ wrapperDepth: 0,
9889
+ inlineResolved: false,
9890
+ mediaCandidateCount: 0,
9891
+ supportedMediaCount: 0,
9892
+ playStarted: false,
9893
+ impressionFired: false,
9894
+ startedAt: Date.now()
9895
+ });
9896
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9897
+ breakId: this.timing.adBreakEpoch,
9898
+ requestId: requestToken,
9899
+ controllerId: this.controllerGeneration
9900
+ });
9901
+ }
9902
+ },
9903
+ {
9904
+ key: "isAdLoadingWithoutPlayback",
9905
+ value: function isAdLoadingWithoutPlayback() {
9906
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9907
+ }
9908
+ },
9909
+ {
9910
+ key: "noteStopBeforeStart",
9911
+ value: function noteStopBeforeStart(reason) {
9912
+ if (!this.isAdLoadingWithoutPlayback()) return;
9913
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9914
+ reason: reason,
9915
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9916
+ });
9917
+ }
9918
+ },
9919
+ {
9920
+ key: "handleRequestWatchdogTimeout",
9921
+ value: function handleRequestWatchdogTimeout() {
9922
+ var adPlayer = this.host.getAdPlayer();
9923
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9924
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9925
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9926
+ });
9927
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9928
+ return;
9929
+ }
9930
+ this.handleAdFailure("request_watchdog_timeout");
9931
+ }
9932
+ },
9933
+ {
9934
+ key: "callController",
9935
+ value: function callController(call) {
8962
9936
  return _async_to_generator(function() {
8963
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
8964
9937
  return _ts_generator(this, function(_state) {
8965
9938
  switch(_state.label){
8966
9939
  case 0:
8967
- adPlayer = this.host.getAdPlayer();
8968
- if (adPlayer.isAdPlaying()) return [
9940
+ this.controllerCallInFlight = true;
9941
+ _state.label = 1;
9942
+ case 1:
9943
+ _state.trys.push([
9944
+ 1,
9945
+ ,
9946
+ 3,
9947
+ 4
9948
+ ]);
9949
+ return [
9950
+ 4,
9951
+ call()
9952
+ ];
9953
+ case 2:
9954
+ _state.sent();
9955
+ return [
9956
+ 3,
9957
+ 4
9958
+ ];
9959
+ case 3:
9960
+ this.controllerCallInFlight = false;
9961
+ return [
9962
+ 7
9963
+ ];
9964
+ case 4:
9965
+ return [
8969
9966
  2
8970
9967
  ];
9968
+ }
9969
+ });
9970
+ }).call(this);
9971
+ }
9972
+ },
9973
+ {
9974
+ key: "playSingleAd",
9975
+ value: function playSingleAd(vastTagUrl) {
9976
+ var trigger = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "vmap";
9977
+ return _async_to_generator(function() {
9978
+ var epoch, generation, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, error;
9979
+ return _ts_generator(this, function(_state) {
9980
+ switch(_state.label){
9981
+ case 0:
9982
+ if (this.slotState === "REQUESTING" || this.slotState === "READY" || this.slotState === "PLAYING" || this.slotState === "ENDING") {
9983
+ this.logOrchestratorFunnel("request_suppressed", {
9984
+ trigger: trigger,
9985
+ state: this.slotState,
9986
+ why: "request_in_flight"
9987
+ });
9988
+ return [
9989
+ 2
9990
+ ];
9991
+ }
8971
9992
  if (this.timing.failedVastUrls.has(vastTagUrl)) {
8972
9993
  if (this.debug) console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:", vastTagUrl);
9994
+ this.timing.consecutiveFailures++;
8973
9995
  throw new Error("VAST URL permanently failed");
8974
9996
  }
8975
9997
  if (this.timing.isUrlInCooldown(vastTagUrl)) {
8976
9998
  if (this.debug) console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):", vastTagUrl);
9999
+ this.timing.consecutiveFailures++;
8977
10000
  throw new Error("VAST URL in cooldown after no-fill");
8978
10001
  }
8979
10002
  if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
@@ -8984,16 +10007,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8984
10007
  if (this.debug) console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request");
8985
10008
  throw new Error("GAM in cooldown");
8986
10009
  }
8987
- this.recreateAdController();
10010
+ epoch = this.timing.adBreakEpoch;
10011
+ this.recreateAdController("new_request");
10012
+ generation = this.controllerGeneration;
8988
10013
  requestToken = ++this.timing.adRequestTokenCounter;
8989
10014
  this.timing.activeAdRequestToken = requestToken;
10015
+ ap = this.host.getAdPlayer();
10016
+ requestUrl = this.withCurrentPodBudget(vastTagUrl);
10017
+ this.currentVastUrl = requestUrl;
10018
+ this.setSlotState("REQUESTING", trigger);
10019
+ this.beginFunnelRequest(ap, requestToken, trigger);
8990
10020
  _state.label = 1;
8991
10021
  case 1:
8992
10022
  _state.trys.push([
8993
10023
  1,
8994
- 8,
10024
+ 5,
8995
10025
  ,
8996
- 9
10026
+ 6
8997
10027
  ]);
8998
10028
  return [
8999
10029
  4,
@@ -9001,265 +10031,87 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9001
10031
  ];
9002
10032
  case 2:
9003
10033
  _state.sent();
10034
+ if (this.isStale(epoch, generation)) return [
10035
+ 2
10036
+ ];
9004
10037
  this.timing.startAdRequestWatchdog(requestToken);
9005
- this.timing.lastAdRequestTime = Date.now();
9006
- ap = this.host.getAdPlayer();
9007
- requestUrl = this.withCurrentPodBudget(vastTagUrl);
9008
- this.currentVastUrl = requestUrl;
9009
10038
  return [
9010
10039
  4,
9011
- ap.requestAds(requestUrl)
10040
+ this.callController(function() {
10041
+ return ap.requestAds(requestUrl);
10042
+ })
9012
10043
  ];
9013
10044
  case 3:
9014
10045
  _state.sent();
10046
+ this.timing.clearAdRequestWatchdog();
10047
+ if (this.isStale(epoch, generation)) {
10048
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
10049
+ requestId: requestToken
10050
+ });
10051
+ return [
10052
+ 2
10053
+ ];
10054
+ }
9015
10055
  sendAdLoadedTracking(this.host.config.licenseKey, {
9016
10056
  source: "hls",
9017
10057
  vastUrl: requestUrl,
9018
10058
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
9019
10059
  }, this.analyticsContext).catch(function() {});
9020
- this.timing.clearAdRequestWatchdog();
9021
- if (this.timing.activeAdRequestToken !== requestToken) return [
9022
- 2
9023
- ];
9024
10060
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
9025
- this.timing.rejectLoadedAdForDuration(ap);
9026
- this.recreateAdController();
10061
+ ;
10062
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
10063
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
10064
+ this.logOrchestratorFunnel("discarded_budget", {
10065
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
10066
+ remainingMs: remainingMs
10067
+ });
9027
10068
  throw new Error("ad_duration_exceeds_budget");
9028
10069
  }
9029
- _state.label = 4;
9030
- case 4:
9031
- _state.trys.push([
9032
- 4,
9033
- 6,
9034
- ,
9035
- 7
9036
- ]);
10070
+ this.setSlotState("READY", "vast_ready");
9037
10071
  this.timing.startAdFailsafeTimer(requestToken);
9038
10072
  return [
9039
10073
  4,
9040
- ap.play()
10074
+ this.callController(function() {
10075
+ return ap.play();
10076
+ })
9041
10077
  ];
9042
- case 5:
10078
+ case 4:
9043
10079
  _state.sent();
9044
- this.timing.markAdStarted();
10080
+ if (this.isStale(epoch, generation)) return [
10081
+ 2
10082
+ ];
9045
10083
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
9046
10084
  this.timing.scheduleAdStopAtBreakBoundary();
9047
10085
  }
9048
10086
  ap.setAdVolume(getAdAudioVolume(ap));
9049
- this.timing.consecutiveFailures = 0;
9050
10087
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9051
10088
  return [
9052
10089
  3,
9053
- 7
9054
- ];
9055
- case 6:
9056
- playError = _state.sent();
9057
- if (this.debug) console.error("[AD-ERROR] Failed to play ad:", playError);
9058
- if (this.timing.isTemporaryAdError(playError)) {
9059
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9060
- if (this.debug) console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown");
9061
- } else {
9062
- this.timing.failedVastUrls.add(vastTagUrl);
9063
- if (this.debug) console.log("[AD-ERROR] Permanent play error - URL blacklisted");
9064
- }
9065
- this.timing.clearAdFailsafeTimer();
9066
- if (this.timing.activeAdRequestToken === requestToken) {
9067
- this.timing.activeAdRequestToken = null;
9068
- }
9069
- throw playError;
9070
- case 7:
9071
- return [
9072
- 3,
9073
- 9
10090
+ 6
9074
10091
  ];
9075
- case 8:
10092
+ case 5:
9076
10093
  error = _state.sent();
9077
- errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "";
9078
- if (this.debug) console.error("[AD-ERROR] Ad request failed:", errorMessage);
9079
- if (this.timing.isTemporaryAdError(error)) {
9080
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9081
- if (this.debug) console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown");
9082
- } else {
9083
- this.timing.failedVastUrls.add(vastTagUrl);
9084
- if (this.debug) console.log("[AD-ERROR] Permanent error - URL blacklisted:", errorMessage);
9085
- }
9086
10094
  this.timing.clearAdRequestWatchdog();
9087
10095
  this.timing.clearAdFailsafeTimer();
9088
10096
  if (this.timing.activeAdRequestToken === requestToken) {
9089
10097
  this.timing.activeAdRequestToken = null;
9090
10098
  }
9091
- throw error;
9092
- case 9:
9093
- return [
9094
- 2
9095
- ];
9096
- }
9097
- });
9098
- }).call(this);
9099
- }
9100
- },
9101
- {
9102
- key: "showPlaceholderAndWaitForAds",
9103
- value: // ───────────────────────────────────────────────────────────────
9104
- // Placeholder wait
9105
- // ───────────────────────────────────────────────────────────────
9106
- function showPlaceholderAndWaitForAds() {
9107
- return _async_to_generator(function() {
9108
- var remaining, waitTime, checkInterval, maxChecks, i, nextAdUrl, error, errorMessage;
9109
- return _ts_generator(this, function(_state) {
9110
- switch(_state.label){
9111
- case 0:
9112
- remaining = this.timing.getRemainingAdMs();
9113
- waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);
9114
- if (this.timing.isGamInCooldown()) {
9115
- if (this.debug) console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait");
9116
- this.handleAdPodComplete();
9117
- return [
9118
- 2
9119
- ];
9120
- }
9121
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9122
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures");
9123
- this.handleAdPodComplete();
9124
- return [
9125
- 2
9126
- ];
9127
- }
9128
- if (waitTime < 1e3) {
9129
- this.handleAdPodComplete();
10099
+ if (this.isStale(epoch, generation)) {
10100
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
10101
+ requestId: requestToken,
10102
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
10103
+ });
9130
10104
  return [
9131
10105
  2
9132
10106
  ];
9133
10107
  }
9134
- if (this.debug) {
9135
- console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(waitTime, "ms while waiting for ad URLs"));
9136
- }
9137
- this.isShowingPlaceholder = true;
9138
- this.host.getAdPlayer().showPlaceholder();
9139
- checkInterval = 300;
9140
- maxChecks = Math.floor(waitTime / checkInterval);
9141
- i = 0;
9142
- _state.label = 1;
9143
- case 1:
9144
- if (!(i < maxChecks)) return [
9145
- 3,
9146
- 12
9147
- ];
9148
- return [
9149
- 4,
9150
- new Promise(function(resolve) {
9151
- return setTimeout(resolve, checkInterval);
9152
- })
9153
- ];
9154
- case 2:
9155
- _state.sent();
9156
- if (!this.inAdBreak) return [
9157
- 2
9158
- ];
9159
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9160
- if (this.debug) console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait");
9161
- return [
9162
- 3,
9163
- 12
9164
- ];
9165
- }
9166
- if (!this.timing.hasTimeToStartAnotherAd()) {
9167
- if (this.debug) console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break");
9168
- return [
9169
- 3,
9170
- 12
9171
- ];
10108
+ if (this.debug) console.error("[AD-ERROR] Ad request failed:", error === null || error === void 0 ? void 0 : error.message);
10109
+ this.recordRequestFailure(error, vastTagUrl);
10110
+ if ((error === null || error === void 0 ? void 0 : error.message) === "ad_duration_exceeds_budget") {
10111
+ this.recreateAdController("discarded_budget");
9172
10112
  }
9173
- _state.label = 3;
9174
- case 3:
9175
- if (!(this.adRequestQueue.length > 0)) return [
9176
- 3,
9177
- 11
9178
- ];
9179
- if (!this.timing.hasTimeToStartAnotherAd()) return [
9180
- 3,
9181
- 11
9182
- ];
9183
- nextAdUrl = this.adRequestQueue.shift();
9184
- if (!nextAdUrl) return [
9185
- 3,
9186
- 3
9187
- ];
9188
- if (this.timing.failedVastUrls.has(nextAdUrl)) return [
9189
- 3,
9190
- 3
9191
- ];
9192
- if (this.timing.isUrlInCooldown(nextAdUrl)) return [
9193
- 3,
9194
- 3
9195
- ];
9196
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player");
9197
- this.isShowingPlaceholder = false;
9198
- this.host.getAdPlayer().hidePlaceholder();
9199
- _state.label = 4;
9200
- case 4:
9201
- _state.trys.push([
9202
- 4,
9203
- 6,
9204
- ,
9205
- 10
9206
- ]);
9207
- return [
9208
- 4,
9209
- this.playSingleAd(nextAdUrl)
9210
- ];
9211
- case 5:
9212
- _state.sent();
9213
- this.timing.consecutiveFailures = 0;
9214
- return [
9215
- 3,
9216
- 10
9217
- ];
10113
+ throw error;
9218
10114
  case 6:
9219
- error = _state.sent();
9220
- errorMessage = error.message;
9221
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
9222
- 3,
9223
- 8
9224
- ];
9225
- return [
9226
- 4,
9227
- this.tryNextAvailableAdWithRateLimit()
9228
- ];
9229
- case 7:
9230
- _state.sent();
9231
- return [
9232
- 2
9233
- ];
9234
- case 8:
9235
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
9236
- this.timing.consecutiveFailures++;
9237
- }
9238
- return [
9239
- 4,
9240
- this.tryNextAvailableAdWithRateLimit()
9241
- ];
9242
- case 9:
9243
- _state.sent();
9244
- return [
9245
- 3,
9246
- 10
9247
- ];
9248
- case 10:
9249
- return [
9250
- 2
9251
- ];
9252
- case 11:
9253
- i++;
9254
- return [
9255
- 3,
9256
- 1
9257
- ];
9258
- case 12:
9259
- if (this.debug) console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break");
9260
- this.isShowingPlaceholder = false;
9261
- this.host.getAdPlayer().hidePlaceholder();
9262
- this.handleAdPodComplete();
9263
10115
  return [
9264
10116
  2
9265
10117
  ];
@@ -9272,26 +10124,136 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9272
10124
  // ───────────────────────────────────────────────────────────────
9273
10125
  // Ad break completion
9274
10126
  // ───────────────────────────────────────────────────────────────
10127
+ key: "logBreakFunnel",
10128
+ value: function logBreakFunnel(endReason) {
10129
+ var funnel = this.breakFunnel;
10130
+ this.breakFunnel = {};
10131
+ if (Object.keys(funnel).length === 0) return;
10132
+ var count = function count(stage) {
10133
+ var _funnel_stage;
10134
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
10135
+ };
10136
+ var countPrefix = function countPrefix(prefix) {
10137
+ return Object.keys(funnel).reduce(function(total, stage) {
10138
+ var _funnel_stage;
10139
+ return stage.indexOf(prefix) === 0 ? total + ((_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0) : total;
10140
+ }, 0);
10141
+ };
10142
+ var breakId = this.opportunityEpoch;
10143
+ var requestRetries = count("gam_http_request_retry");
10144
+ var requests = count("gam_http_request_sent") - requestRetries;
10145
+ if (requests > 0 && count("impression_fired") === 0) {
10146
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
10147
+ breakId: breakId,
10148
+ requests: requests,
10149
+ endReason: endReason
10150
+ });
10151
+ }
10152
+ console.log("[AdBreak][FUNNEL] Break summary", {
10153
+ breakId: breakId,
10154
+ endReason: endReason,
10155
+ opportunities: count("opportunity_created"),
10156
+ vastUrlsGenerated: count("vast_url_generated"),
10157
+ requests: requests,
10158
+ requestRetries: requestRetries,
10159
+ gamResponses: count("gam_response_received"),
10160
+ requestsSuppressed: count("request_suppressed"),
10161
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10162
+ filled: count("vast_received"),
10163
+ noFill: count("no_fill"),
10164
+ fillRejected: count("vast_fill_rejected"),
10165
+ gamAdWithoutImpression: count("gam_ad_without_impression"),
10166
+ playbackFailedAfterFill: count("request_outcome:playback_failed"),
10167
+ requestFailed: count("request_failed"),
10168
+ requestAbortedTimeout: count("request_aborted_timeout"),
10169
+ credentialsRetries: count("vast_credentials_retry"),
10170
+ wrapperFailures: count("wrapper_fetch:failure"),
10171
+ noSupportedMedia: count("vast_no_supported_media"),
10172
+ vpaidOnly: count("vast_no_supported_media:vpaid"),
10173
+ audioOnly: count("vast_no_supported_media:audio_only"),
10174
+ mediaFilesEvaluated: count("mediafile_evaluated"),
10175
+ mediaFilesAccepted: count("mediafile_evaluated:accepted"),
10176
+ controllerDestroys: countPrefix("controller_destroy:"),
10177
+ staleCallbacks: count("stale_callback_ignored") + count("stale_request_result_ignored"),
10178
+ tagAllowsAudio: count("tag_allows_audio"),
10179
+ missingImpression: count("vast_missing_impression"),
10180
+ discardedBudget: count("discarded_budget"),
10181
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10182
+ mediaRejected: count("media_candidate:rejected"),
10183
+ mediaFallbacks: count("media_fallback"),
10184
+ playCalled: count("play_called"),
10185
+ playRejected: count("play_rejected"),
10186
+ mutedRetry: count("muted_retry"),
10187
+ startTimeouts: count("play_resolved_but_never_started"),
10188
+ impressions: count("impression_fired"),
10189
+ impressionUrls: count("impression_urls"),
10190
+ trackingRequests: count("tracking_request_created"),
10191
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10192
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10193
+ trackingInvalidUrls: count("tracking_url_invalid"),
10194
+ vastAdFallbacks: count("vast_ad_fallback"),
10195
+ mediaEvents: count("media_event"),
10196
+ quartile25: count("first_quartile"),
10197
+ quartile50: count("midpoint"),
10198
+ quartile75: count("third_quartile"),
10199
+ complete: count("complete"),
10200
+ stoppedBeforeStart: count("stopped_before_start"),
10201
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10202
+ unexpectedUnmutes: count("unexpected_unmute"),
10203
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10204
+ visibilityHidden: count("while_hidden"),
10205
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10206
+ stages: funnel
10207
+ });
10208
+ }
10209
+ },
10210
+ {
9275
10211
  key: "handleAdPodComplete",
9276
10212
  value: function handleAdPodComplete() {
10213
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "unspecified";
9277
10214
  if (this.debug) {
9278
- console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up");
10215
+ console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up", {
10216
+ reason: reason
10217
+ });
10218
+ }
10219
+ var previousState = this.slotState;
10220
+ var alreadyEnded = previousState === "IDLE" && !this.inAdBreak;
10221
+ this.setSlotState("ENDING", reason);
10222
+ this.cancelScheduledRequest();
10223
+ var adPlayer = this.host.getAdPlayer();
10224
+ if (previousState === "REQUESTING") {
10225
+ var _adPlayer_abortPendingRequest;
10226
+ (_adPlayer_abortPendingRequest = adPlayer.abortPendingRequest) === null || _adPlayer_abortPendingRequest === void 0 ? void 0 : _adPlayer_abortPendingRequest.call(adPlayer, "VAST request aborted: ad break ended (".concat(reason, ")"));
10227
+ }
10228
+ if (!alreadyEnded) {
10229
+ console.log("[AD-CONTROLLER] stop", {
10230
+ controllerId: this.controllerGeneration,
10231
+ requestId: this.currentRequestId,
10232
+ state: previousState,
10233
+ reason: reason
10234
+ });
9279
10235
  }
10236
+ this.finalizeRequestDiagnostics(this.currentRequestId, "break_ended:".concat(reason));
10237
+ this.currentRequestId = void 0;
9280
10238
  this.timing.resetForBreakEnd();
9281
- this.stopContinuousFetching();
10239
+ this.placeholder.hide();
9282
10240
  this.clearPendingAdBreak();
9283
10241
  if (this.isShowingPlaceholder) {
9284
- this.host.getAdPlayer().hidePlaceholder();
10242
+ adPlayer.hidePlaceholder();
9285
10243
  this.isShowingPlaceholder = false;
9286
10244
  }
9287
- this.adRequestQueue = [];
9288
10245
  this.inAdBreak = false;
9289
10246
  this.adDetectSentForCurrentBreak = false;
9290
10247
  this.cueManager.activeScte35BreakKey = void 0;
9291
10248
  this.cueManager.scheduledScte35BreakKey = void 0;
9292
10249
  this.adPodQueue = [];
9293
10250
  this.showAds = false;
9294
- this.host.getAdPlayer().stop().catch(function() {});
10251
+ this.breakSource = void 0;
10252
+ this.followUpBaseVastUrl = void 0;
10253
+ this.unusableResponsesInBreak = 0;
10254
+ adPlayer.stop().catch(function() {});
10255
+ if (!alreadyEnded) this.logBreakFunnel(reason);
10256
+ this.setSlotState("IDLE", "break_complete");
9295
10257
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9296
10258
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9297
10259
  if (this.host.video.muted !== restoredMuted) {
@@ -9585,25 +10547,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9585
10547
  {
9586
10548
  key: "handleAdFailure",
9587
10549
  value: function handleAdFailure() {
9588
- this.timing.consecutiveFailures++;
9589
- this.timing.recordGamNoFill();
9590
- var remaining = this.timing.getRemainingAdMs();
9591
- if (this.debug) {
9592
- 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 ? {
9593
- queuedUrls: _to_consumable_array(this.adRequestQueue)
9594
- } : {});
9595
- }
9596
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9597
- if (this.debug) console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
9598
- this.handleAdPodComplete();
10550
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "ad_failure";
10551
+ if (!this.inAdBreak) return;
10552
+ if (this.slotState === "REQUESTING" || this.slotState === "ENDING") {
10553
+ this.logOrchestratorFunnel("failure_deferred_to_request", {
10554
+ reason: reason,
10555
+ state: this.slotState
10556
+ });
9599
10557
  return;
9600
10558
  }
9601
- if (this.timing.hasTimeToStartAnotherAd()) {
9602
- this.tryNextAvailableAdWithRateLimit();
9603
- } else {
9604
- if (this.debug) console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:", this.timing.failedVastUrls.size);
9605
- this.handleAdPodComplete();
10559
+ this.timing.consecutiveFailures++;
10560
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
10561
+ if (diag && !diag.failureReason) diag.failureReason = reason;
10562
+ if (this.debug) {
10563
+ console.log("[AdBreak] Ad failure (".concat(reason, "): remaining=").concat(this.timing.getRemainingAdMs(), "ms, consecutiveFailures=").concat(this.timing.consecutiveFailures));
9606
10564
  }
10565
+ this.setSlotState("NEEDS_NEXT_AD", reason);
10566
+ this.requestNextAd(reason);
9607
10567
  }
9608
10568
  }
9609
10569
  ]);
@@ -9643,10 +10603,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9643
10603
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9644
10604
  },
9645
10605
  onWatchdogTimeout: function onWatchdogTimeout() {
9646
- return _this.adBreak.handleAdFailure();
10606
+ return _this.adBreak.handleRequestWatchdogTimeout();
9647
10607
  },
9648
10608
  onFailsafeTimeout: function onFailsafeTimeout() {
9649
- return _this.adBreak.handleAdFailure();
10609
+ return _this.adBreak.handleAdFailure("failsafe_timeout");
9650
10610
  },
9651
10611
  getAdState: function getAdState() {
9652
10612
  return {
@@ -9748,6 +10708,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9748
10708
  licenseKey: this.config.licenseKey
9749
10709
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9750
10710
  mainHlsInstance: this.hlsEngine.hls
10711
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10712
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9751
10713
  } : {}));
9752
10714
  }
9753
10715
  },
@@ -9894,6 +10856,21 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9894
10856
  adBehavior: adBehavior
9895
10857
  });
9896
10858
  }
10859
+ if (this.adBreak.isBreakActive()) {
10860
+ console.log("[AD-CONTROLLER] destroy skipped", {
10861
+ reason: "manifest_parsed_during_break",
10862
+ state: this.adBreak.getSlotState()
10863
+ });
10864
+ return [
10865
+ 2
10866
+ ];
10867
+ }
10868
+ if (this.debug) {
10869
+ console.log("[AD-CONTROLLER] destroy", {
10870
+ reason: "manifest_parsed",
10871
+ state: "IDLE"
10872
+ });
10873
+ }
9897
10874
  this.adPlayer.destroy();
9898
10875
  this.adPlayer = this.createAdPlayer(this.shouldContinueLiveStreamDuringAds());
9899
10876
  this.adPlayer.initialize();
@@ -10075,9 +11052,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10075
11052
  this.timing.setAdBreakDurationBoundary(marker.durationSeconds * 1e3);
10076
11053
  }
10077
11054
  this.timing.scheduleAdStopAtBreakBoundary();
10078
- if (!this.adPlayer.isAdPlaying() && this.timing.activeAdRequestToken === null && this.adBreak.adRequestQueue.length > 0 && this.timing.hasTimeToStartAnotherAd()) {
10079
- this.adBreak.tryNextAvailableAdWithRateLimit();
10080
- }
10081
11055
  return;
10082
11056
  }
10083
11057
  if (marker.type === "end") {
@@ -10089,12 +11063,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10089
11063
  }
10090
11064
  var remaining = this.timing.getRemainingAdMs();
10091
11065
  var adPlaying = this.adPlayer.isAdPlaying();
10092
- var hasQueuedAds = this.adBreak.adRequestQueue.length > 0;
10093
11066
  if (this.debug) {
10094
11067
  console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:", {
10095
11068
  remaining: remaining,
10096
11069
  adPlaying: adPlaying,
10097
- hasQueuedAds: hasQueuedAds,
11070
+ adSlotState: this.adBreak.getSlotState(),
10098
11071
  activeAdRequest: this.timing.activeAdRequestToken !== null
10099
11072
  });
10100
11073
  }
@@ -10102,9 +11075,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10102
11075
  this.timing.clearAdStartTimer();
10103
11076
  this.timing.clearAdStopTimer();
10104
11077
  if (adPlaying) {
11078
+ this.adBreak.noteStopBeforeStart("scte_end");
10105
11079
  this.adPlayer.stop().catch(function() {});
10106
11080
  }
10107
- this.adBreak.handleAdPodComplete();
11081
+ this.adBreak.handleAdPodComplete("scte_end");
10108
11082
  return;
10109
11083
  }
10110
11084
  }
@@ -10112,6 +11086,15 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10112
11086
  {
10113
11087
  key: "startScte35AdBreak",
10114
11088
  value: function startScte35AdBreak(marker, cueKey, durationMs) {
11089
+ if (this.adBreak.isBreakActive()) {
11090
+ if (this.debug) {
11091
+ console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 break start: a break is already active", {
11092
+ state: this.adBreak.getSlotState(),
11093
+ cueKey: cueKey
11094
+ });
11095
+ }
11096
+ return;
11097
+ }
10115
11098
  this.adBreak.inAdBreak = true;
10116
11099
  this.cueManager.activeScte35BreakKey = cueKey !== null && cueKey !== void 0 ? cueKey : this.cueManager.pendingScte35CueKey;
10117
11100
  this.cueManager.scheduledScte35BreakKey = void 0;
@@ -10141,9 +11124,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10141
11124
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10142
11125
  }
10143
11126
  if (adPlaying) {
11127
+ this.adBreak.noteStopBeforeStart("break_boundary");
10144
11128
  this.adPlayer.stop().catch(function() {});
10145
11129
  }
10146
- this.adBreak.handleAdPodComplete();
11130
+ this.adBreak.handleAdPodComplete("break_boundary");
10147
11131
  }
10148
11132
  },
10149
11133
  {
@@ -10153,14 +11137,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10153
11137
  key: "startAdPrefetch",
10154
11138
  value: function startAdPrefetch(marker, fragmentSn, cueKey) {
10155
11139
  if (this.adBreak.pendingAdBreak || this.adBreak.inAdBreak) return;
10156
- var scheduled = this.adConfig.findCurrentOrNextBreak(this.video.currentTime * 1e3);
10157
- var tags = this.adConfig.selectVastTagsForBreak(scheduled);
10158
- var baseVastUrl;
10159
- if (tags && tags.length > 0 && tags[0]) {
10160
- baseVastUrl = tags[0];
10161
- } else if (this.adConfig.apiVastTagUrl) {
10162
- baseVastUrl = this.adConfig.apiVastTagUrl;
10163
- } else {
11140
+ var baseVastUrl = this.adConfig.apiVastTagUrl;
11141
+ if (!baseVastUrl) {
10164
11142
  if (this.debug) console.warn("[StormcloudVideoPlayer] No VAST URL available for prefetch");
10165
11143
  return;
10166
11144
  }
@@ -10190,8 +11168,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10190
11168
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
10191
11169
  }, detectPayload), buildAnalyticsContext(this.config)).catch(function() {});
10192
11170
  if (this.debug) {
10193
- console.log("[PREFETCH] Starting ad prefetch for upcoming ad break");
10194
- console.log("[PREFETCH] Pre-generated pod request URL");
11171
+ console.log("[PREFETCH] Pre-generated pod request URL for upcoming ad break");
10195
11172
  }
10196
11173
  }
10197
11174
  },
@@ -10202,7 +11179,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10202
11179
  key: "onTimeUpdate",
10203
11180
  value: function onTimeUpdate(currentTimeSec) {
10204
11181
  var _this = this;
10205
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11182
+ if (this.adConfig.vmapBreaks.length === 0) return;
10206
11183
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10207
11184
  var nowMs = currentTimeSec * 1e3;
10208
11185
  var breakToPlay = this.adConfig.findBreakForTime(nowMs);
@@ -10219,7 +11196,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10219
11196
  key: "onVideoEnded",
10220
11197
  value: function onVideoEnded() {
10221
11198
  var _this = this;
10222
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11199
+ if (this.adConfig.vmapBreaks.length === 0) return;
10223
11200
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10224
11201
  var durationMs = Number.isFinite(this.video.duration) ? Math.floor(this.video.duration * 1e3) : 0;
10225
11202
  var postroll = this.adConfig.vmapBreaks.find(function(b) {
@@ -10269,6 +11246,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10269
11246
  this.adBreak.showAds = true;
10270
11247
  this.adBreak.inAdBreak = true;
10271
11248
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11249
+ if (durationMs > 0) {
11250
+ this.timing.setAdBreakDurationBoundary(durationMs);
11251
+ }
11252
+ this.adBreak.beginVmapBreak(key);
10272
11253
  _state.label = 1;
10273
11254
  case 1:
10274
11255
  _state.trys.push([
@@ -10279,7 +11260,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10279
11260
  ]);
10280
11261
  return [
10281
11262
  4,
10282
- this.adBreak.playSingleAd(first)
11263
+ this.adBreak.playSingleAd(first, "vmap")
10283
11264
  ];
10284
11265
  case 2:
10285
11266
  _state.sent();
@@ -10292,7 +11273,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10292
11273
  if (this.debug) {
10293
11274
  console.warn("[StormcloudVideoPlayer] VMAP ad request failed:", error);
10294
11275
  }
10295
- this.adBreak.handleAdPodComplete();
11276
+ this.adBreak.continueAfterRequestFailure();
10296
11277
  return [
10297
11278
  3,
10298
11279
  4
@@ -10434,7 +11415,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10434
11415
  key: "destroy",
10435
11416
  value: function destroy() {
10436
11417
  var _this_adPlayer;
10437
- this.adBreak.stopContinuousFetching();
11418
+ this.adBreak.cancelScheduledRequest();
10438
11419
  this.timing.destroy();
10439
11420
  this.adBreak.clearPendingAdBreak();
10440
11421
  this.placeholder.destroy();
@@ -10458,7 +11439,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10458
11439
  this.palNonce.sendPlaybackEnd();
10459
11440
  }
10460
11441
  this.palNonce.reset();
10461
- this.adBreak.adRequestQueue = [];
10462
11442
  this.timing.consecutiveFailures = 0;
10463
11443
  }
10464
11444
  }