stormcloud-video-player 0.8.65 → 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.
@@ -1,12 +1,4 @@
1
1
  "use strict";
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_without_holes(arr) {
8
- if (Array.isArray(arr)) return _array_like_to_array(arr);
9
- }
10
2
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
3
  try {
12
4
  var info = gen[key](arg);
@@ -61,14 +53,6 @@ function _define_property(obj, key, value) {
61
53
  } else obj[key] = value;
62
54
  return obj;
63
55
  }
64
- function _iterable_to_array(iter) {
65
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
66
- return Array.from(iter);
67
- }
68
- }
69
- function _non_iterable_spread() {
70
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
71
- }
72
56
  function _object_spread(target) {
73
57
  for(var i = 1; i < arguments.length; i++){
74
58
  var source = arguments[i] != null ? arguments[i] : {};
@@ -107,8 +91,41 @@ function _object_spread_props(target, source) {
107
91
  }
108
92
  return target;
109
93
  }
110
- function _to_consumable_array(arr) {
111
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
94
+ function _object_without_properties(source, excluded) {
95
+ if (source == null) return {};
96
+ var target = {}, sourceKeys, key, i;
97
+ if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
98
+ sourceKeys = Reflect.ownKeys(Object(source));
99
+ for(i = 0; i < sourceKeys.length; i++){
100
+ key = sourceKeys[i];
101
+ if (excluded.indexOf(key) >= 0) continue;
102
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
103
+ target[key] = source[key];
104
+ }
105
+ return target;
106
+ }
107
+ target = _object_without_properties_loose(source, excluded);
108
+ if (Object.getOwnPropertySymbols) {
109
+ sourceKeys = Object.getOwnPropertySymbols(source);
110
+ for(i = 0; i < sourceKeys.length; i++){
111
+ key = sourceKeys[i];
112
+ if (excluded.indexOf(key) >= 0) continue;
113
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
114
+ target[key] = source[key];
115
+ }
116
+ }
117
+ return target;
118
+ }
119
+ function _object_without_properties_loose(source, excluded) {
120
+ if (source == null) return {};
121
+ var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
122
+ for(i = 0; i < sourceKeys.length; i++){
123
+ key = sourceKeys[i];
124
+ if (excluded.indexOf(key) >= 0) continue;
125
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
126
+ target[key] = source[key];
127
+ }
128
+ return target;
112
129
  }
113
130
  function _ts_generator(thisArg, body) {
114
131
  var f, y, t, _ = {
@@ -209,38 +226,10 @@ function _ts_generator(thisArg, body) {
209
226
  };
210
227
  }
211
228
  }
212
- function _ts_values(o) {
213
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
214
- if (m) {
215
- return m.call(o);
216
- }
217
- if (o && typeof o.length === "number") {
218
- return {
219
- next: function() {
220
- if (o && i >= o.length) {
221
- o = void 0;
222
- }
223
- return {
224
- value: o && o[i++],
225
- done: !o
226
- };
227
- }
228
- };
229
- }
230
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
231
- }
232
229
  function _type_of(obj) {
233
230
  "@swc/helpers - typeof";
234
231
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
235
232
  }
236
- function _unsupported_iterable_to_array(o, minLen) {
237
- if (!o) return;
238
- if (typeof o === "string") return _array_like_to_array(o, minLen);
239
- var n = Object.prototype.toString.call(o).slice(8, -1);
240
- if (n === "Object" && o.constructor) n = o.constructor.name;
241
- if (n === "Map" || n === "Set") return Array.from(n);
242
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
243
- }
244
233
  var __defProp = Object.defineProperty;
245
234
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
246
235
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -1299,7 +1288,35 @@ function sendHeartbeat(_0) {
1299
1288
  function getAdAudioVolume(adPlayer) {
1300
1289
  return adPlayer.getOriginalMutedState() ? 0 : adPlayer.getOriginalVolume();
1301
1290
  }
1291
+ // src/utils/vastMacros.ts
1292
+ var GAM_AD_HOSTS = /* @__PURE__ */ new Set([
1293
+ "pubads.g.doubleclick.net",
1294
+ "securepubads.g.doubleclick.net"
1295
+ ]);
1296
+ function ensureVideoAdType(rawUrl) {
1297
+ try {
1298
+ var url = new URL(rawUrl);
1299
+ if (!GAM_AD_HOSTS.has(url.hostname)) return rawUrl;
1300
+ if (url.searchParams.has("ad_type")) return rawUrl;
1301
+ url.searchParams.set("ad_type", "video");
1302
+ return url.toString();
1303
+ } catch (unused) {
1304
+ return rawUrl;
1305
+ }
1306
+ }
1302
1307
  // src/player/AdBreakOrchestrator.ts
1308
+ var REQUEST_FAILURE_STAGES = /* @__PURE__ */ new Set([
1309
+ "no_fill",
1310
+ "vast_fill_rejected",
1311
+ "request_failed",
1312
+ "media_unsupported",
1313
+ "play_failed",
1314
+ "play_resolved_but_never_started",
1315
+ "hls_fatal",
1316
+ "media_error",
1317
+ "stall",
1318
+ "decode_failure"
1319
+ ]);
1303
1320
  var AdBreakOrchestrator = /*#__PURE__*/ function() {
1304
1321
  function AdBreakOrchestrator(host, timing, adConfig, cueManager, placeholder) {
1305
1322
  _class_call_check(this, AdBreakOrchestrator);
@@ -1307,15 +1324,17 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1307
1324
  this.showAds = false;
1308
1325
  this.isShowingPlaceholder = false;
1309
1326
  this.adDetectSentForCurrentBreak = false;
1310
- this.continuousFetchingActive = false;
1311
- this.continuousFetchLoopRunning = false;
1327
+ this.slotState = "IDLE";
1328
+ this.unusableResponsesInBreak = 0;
1329
+ this.controllerGeneration = 0;
1330
+ this.requestDiagnostics = /* @__PURE__ */ new Map();
1312
1331
  this.breakFunnel = {};
1313
1332
  this.controllerCallInFlight = false;
1314
1333
  this.playbackStartedForCurrentRequest = false;
1315
1334
  this.opportunityEpoch = -1;
1316
- this.adRequestQueue = [];
1317
1335
  this.adPodQueue = [];
1318
- this.maxPlaceholderDurationMs = 5e3;
1336
+ this.defaultMinRemainingMsToRequestAd = 1e4;
1337
+ this.defaultMaxNoFillsPerBreak = 2;
1319
1338
  this.pendingAdBreak = null;
1320
1339
  this.host = host;
1321
1340
  this.timing = timing;
@@ -1351,7 +1370,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1351
1370
  key: "attachImaEventListeners",
1352
1371
  value: function attachImaEventListeners() {
1353
1372
  var _this = this;
1354
- var adPlayer = this.host.getAdPlayer();
1373
+ var controller = this.host.getAdPlayer();
1374
+ var generation = this.controllerGeneration;
1375
+ var adPlayer = {
1376
+ on: function on(event, handler) {
1377
+ controller.on(event, function(payload) {
1378
+ if (generation !== _this.controllerGeneration) {
1379
+ _this.logOrchestratorFunnel("stale_callback_ignored", {
1380
+ event: event,
1381
+ staleControllerId: generation,
1382
+ currentControllerId: _this.controllerGeneration
1383
+ });
1384
+ return;
1385
+ }
1386
+ handler(payload);
1387
+ });
1388
+ }
1389
+ };
1355
1390
  adPlayer.on("pod_ad_started", function(payload) {
1356
1391
  _this.timing.notePodAdStarted();
1357
1392
  if (_this.debug) {
@@ -1367,19 +1402,29 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1367
1402
  });
1368
1403
  adPlayer.on("ad_funnel", function(payload) {
1369
1404
  if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
1370
- _this.countFunnelStage(payload.stage);
1405
+ var stage = payload.stage;
1406
+ _this.countFunnelStage(stage);
1371
1407
  if (payload.reason) {
1372
- _this.countFunnelStage("".concat(payload.stage, ":").concat(payload.reason));
1408
+ _this.countFunnelStage("".concat(stage, ":").concat(payload.reason));
1373
1409
  }
1374
- if (payload.stage === "impression_fired" && payload.pixelCount != null) {
1410
+ if (stage === "impression_fired" && payload.pixelCount != null) {
1375
1411
  _this.countFunnelStage("impression_urls", payload.pixelCount);
1376
1412
  }
1377
1413
  if (payload.visibilityState === "hidden") {
1378
1414
  _this.countFunnelStage("while_hidden");
1379
1415
  }
1416
+ if (stage === "gam_http_request_sent") {
1417
+ if (payload.attempt === 1) {
1418
+ _this.timing.noteAdRequestSent();
1419
+ } else {
1420
+ _this.countFunnelStage("gam_http_request_retry");
1421
+ }
1422
+ }
1423
+ _this.recordRequestDiagnostic(payload);
1380
1424
  });
1381
1425
  adPlayer.on("ad_impression", function() {
1382
1426
  _this.timing.consecutiveFailures = 0;
1427
+ _this.setSlotState("PLAYING", "impression");
1383
1428
  if (!_this.playbackStartedForCurrentRequest) {
1384
1429
  _this.playbackStartedForCurrentRequest = true;
1385
1430
  _this.timing.markAdStarted();
@@ -1398,16 +1443,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1398
1443
  var remaining = _this.timing.getRemainingAdMs();
1399
1444
  _this.timing.consecutiveFailures = 0;
1400
1445
  if (_this.debug) {
1401
- console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
1402
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
1403
- } : {});
1446
+ console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms"));
1404
1447
  }
1405
1448
  if (_this.inAdBreak) {
1406
- if (_this.timing.hasTimeToStartAnotherAd()) {
1407
- _this.tryNextAvailableAdWithRateLimit();
1408
- } else {
1409
- _this.handleAdPodComplete();
1410
- }
1449
+ _this.setSlotState("NEEDS_NEXT_AD", "all_ads_completed");
1450
+ _this.requestNextAd("all_ads_completed");
1411
1451
  }
1412
1452
  });
1413
1453
  adPlayer.on("ad_error", function(errorPayload) {
@@ -1428,10 +1468,9 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1428
1468
  }
1429
1469
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
1430
1470
  if (_this.controllerCallInFlight) {
1431
- _this.timing.recordGamNoFill();
1432
1471
  return;
1433
1472
  }
1434
- _this.handleAdFailure();
1473
+ _this.handleAdFailure("ad_error");
1435
1474
  });
1436
1475
  adPlayer.on("content_pause", function() {
1437
1476
  _this.timing.clearAdFailsafeTimer();
@@ -1470,26 +1509,32 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1470
1509
  }
1471
1510
  _this.timing.consecutiveFailures = 0;
1472
1511
  _this.timing.recordPlayedAdDuration(_this.host.getAdPlayer());
1473
- var remaining = _this.timing.getRemainingAdMs();
1474
1512
  if (_this.debug) {
1475
- console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
1476
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
1477
- } : {});
1478
- }
1479
- if (_this.timing.hasTimeToStartAnotherAd()) {
1480
- _this.tryNextAvailableAdWithRateLimit();
1481
- } else {
1482
- _this.handleAdPodComplete();
1513
+ console.log("[AdBreak] content_resume: remaining=".concat(_this.timing.getRemainingAdMs(), "ms"));
1483
1514
  }
1515
+ _this.setSlotState("NEEDS_NEXT_AD", "ad_complete");
1516
+ _this.requestNextAd("ad_complete");
1484
1517
  });
1485
1518
  }
1486
1519
  },
1487
1520
  {
1488
1521
  key: "recreateAdController",
1489
- value: function recreateAdController() {
1490
- if (this.debug) {
1491
- console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");
1522
+ value: function recreateAdController(reason) {
1523
+ if (reason === "new_request" && (this.slotState === "REQUESTING" || this.slotState === "READY")) {
1524
+ console.warn("[AD-CONTROLLER] destroy during active request", {
1525
+ controllerId: this.controllerGeneration,
1526
+ requestId: this.currentRequestId,
1527
+ state: this.slotState,
1528
+ reason: reason
1529
+ });
1492
1530
  }
1531
+ console.log("[AD-CONTROLLER] destroy", {
1532
+ controllerId: this.controllerGeneration,
1533
+ requestId: this.currentRequestId,
1534
+ state: this.slotState,
1535
+ reason: reason
1536
+ });
1537
+ this.countFunnelStage("controller_destroy:".concat(reason));
1493
1538
  var shouldShowPlaceholder = this.inAdBreak && this.showAds;
1494
1539
  var adPlayer = this.host.getAdPlayer();
1495
1540
  if (shouldShowPlaceholder && adPlayer) {
@@ -1516,9 +1561,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1516
1561
  var continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();
1517
1562
  var newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);
1518
1563
  this.host.setAdPlayer(newAdPlayer);
1564
+ this.controllerGeneration++;
1519
1565
  newAdPlayer.initialize();
1520
1566
  newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);
1521
1567
  this.attachImaEventListeners();
1568
+ if (this.debug) {
1569
+ console.log("[AD-CONTROLLER] create", {
1570
+ controllerId: this.controllerGeneration,
1571
+ reason: reason
1572
+ });
1573
+ }
1522
1574
  if (shouldShowPlaceholder) {
1523
1575
  this.placeholder.show();
1524
1576
  newAdPlayer.showPlaceholder();
@@ -1539,32 +1591,57 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1539
1591
  }
1540
1592
  },
1541
1593
  {
1542
- key: "handleAdStart",
1543
- value: // ───────────────────────────────────────────────────────────────
1594
+ // ───────────────────────────────────────────────────────────────
1544
1595
  // Ad break start
1545
1596
  // ───────────────────────────────────────────────────────────────
1546
- function handleAdStart(_marker) {
1597
+ key: "isBreakActive",
1598
+ value: function isBreakActive() {
1599
+ return this.slotState !== "IDLE";
1600
+ }
1601
+ },
1602
+ {
1603
+ key: "getSlotState",
1604
+ value: function getSlotState() {
1605
+ return this.slotState;
1606
+ }
1607
+ },
1608
+ {
1609
+ key: "beginVmapBreak",
1610
+ value: function beginVmapBreak(breakKey) {
1611
+ this.breakSource = "vmap";
1612
+ this.followUpBaseVastUrl = void 0;
1613
+ this.unusableResponsesInBreak = 0;
1614
+ this.timing.totalAdRequestsInBreak = 0;
1615
+ this.setSlotState("NEEDS_NEXT_AD", "vmap_break_start");
1616
+ this.noteOpportunity("vmap", breakKey);
1617
+ }
1618
+ },
1619
+ {
1620
+ key: "handleAdStart",
1621
+ value: function handleAdStart(marker) {
1547
1622
  return _async_to_generator(function() {
1548
- var scheduled, tags, baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, podPlayed;
1623
+ var baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, epoch, podPlayed;
1549
1624
  return _ts_generator(this, function(_state) {
1550
1625
  switch(_state.label){
1551
1626
  case 0:
1552
- scheduled = this.adConfig.findCurrentOrNextBreak(this.host.video.currentTime * 1e3);
1553
- if (scheduled) {
1554
- this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));
1627
+ if (this.slotState !== "IDLE") {
1628
+ this.logOrchestratorFunnel("duplicate_break_start", {
1629
+ source: "scte35",
1630
+ state: this.slotState
1631
+ });
1632
+ return [
1633
+ 2
1634
+ ];
1555
1635
  }
1556
- tags = this.adConfig.selectVastTagsForBreak(scheduled);
1557
- if (tags && tags.length > 0 && tags[0]) {
1558
- baseVastUrl = tags[0];
1559
- } else if (this.adConfig.apiVastTagUrl) {
1560
- baseVastUrl = this.adConfig.apiVastTagUrl;
1561
- } else {
1636
+ baseVastUrl = this.adConfig.apiVastTagUrl;
1637
+ if (!baseVastUrl) {
1638
+ console.warn("[AdBreak] SCTE-35 break started but no direct VAST tag is configured");
1562
1639
  this.clearPendingAdBreak();
1563
1640
  return [
1564
1641
  2
1565
1642
  ];
1566
1643
  }
1567
- adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled === null || scheduled === void 0 ? void 0 : scheduled.durationMs;
1644
+ adBreakDurationMs = marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.timing.expectedAdBreakDurationMs;
1568
1645
  if (this.debug) {
1569
1646
  mode = this.host.config.isLiveStream ? "LIVE" : "VOD";
1570
1647
  console.log("[CONTINUOUS-FETCH] ".concat(mode, " MODE: Target duration=").concat(adBreakDurationMs, "ms"));
@@ -1572,9 +1649,12 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1572
1649
  this.timing.failedVastUrls.clear();
1573
1650
  this.timing.temporaryFailureUrls.clear();
1574
1651
  this.timing.consecutiveFailures = 0;
1575
- this.continuousFetchingActive = true;
1576
1652
  this.isShowingPlaceholder = false;
1577
1653
  this.timing.totalAdRequestsInBreak = 0;
1654
+ this.breakSource = "scte35";
1655
+ this.followUpBaseVastUrl = baseVastUrl;
1656
+ this.unusableResponsesInBreak = 0;
1657
+ this.setSlotState("NEEDS_NEXT_AD", "scte35_break_start");
1578
1658
  if (this.adConfig.podAssignedByPrefetch) {
1579
1659
  this.adConfig.podAssignedByPrefetch = false;
1580
1660
  } else {
@@ -1593,29 +1673,17 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1593
1673
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
1594
1674
  }
1595
1675
  this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
1676
+ epoch = this.timing.adBreakEpoch;
1596
1677
  return [
1597
1678
  4,
1598
1679
  this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
1599
1680
  ];
1600
1681
  case 1:
1601
1682
  podPlayed = _state.sent();
1602
- if (!!podPlayed) return [
1603
- 3,
1604
- 3
1605
- ];
1606
- if (this.debug) {
1607
- console.log("[POD] Initial pod request did not fill; attempting top-up pod request");
1683
+ if (!podPlayed && this.inAdBreak && epoch === this.timing.adBreakEpoch) {
1684
+ this.setSlotState("NEEDS_NEXT_AD", "initial_request_failed");
1685
+ this.requestNextAd("initial_request_failed");
1608
1686
  }
1609
- this.continuousFetchingActive = true;
1610
- this.startContinuousFetching(baseVastUrl);
1611
- return [
1612
- 4,
1613
- this.tryNextAvailableAdWithRateLimit()
1614
- ];
1615
- case 2:
1616
- _state.sent();
1617
- _state.label = 3;
1618
- case 3:
1619
1687
  return [
1620
1688
  2
1621
1689
  ];
@@ -1631,10 +1699,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1631
1699
  // ───────────────────────────────────────────────────────────────
1632
1700
  function startOptimizedPod(baseVastUrl, breakDurationMs) {
1633
1701
  return _async_to_generator(function() {
1634
- var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
1702
+ var podUrl, prefetched, epoch, generation, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
1635
1703
  return _ts_generator(this, function(_state) {
1636
1704
  switch(_state.label){
1637
1705
  case 0:
1706
+ prefetched = !!(this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0);
1638
1707
  if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {
1639
1708
  podUrl = this.pendingAdBreak.vastUrls[0];
1640
1709
  this.clearPendingAdBreak();
@@ -1647,12 +1716,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1647
1716
  false
1648
1717
  ];
1649
1718
  }
1650
- this.continuousFetchingActive = false;
1651
- this.recreateAdController();
1719
+ this.noteVastUrlGenerated(podUrl, prefetched ? "prefetch" : "break_start");
1720
+ epoch = this.timing.adBreakEpoch;
1721
+ this.recreateAdController("new_request");
1722
+ generation = this.controllerGeneration;
1652
1723
  adPlayer = this.host.getAdPlayer();
1653
1724
  requestToken = ++this.timing.adRequestTokenCounter;
1654
1725
  this.timing.activeAdRequestToken = requestToken;
1655
1726
  this.currentVastUrl = podUrl;
1727
+ this.setSlotState("REQUESTING", "initial_pod");
1728
+ this.beginFunnelRequest(adPlayer, requestToken, "initial_pod");
1656
1729
  _state.label = 1;
1657
1730
  case 1:
1658
1731
  _state.trys.push([
@@ -1667,9 +1740,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1667
1740
  ];
1668
1741
  case 2:
1669
1742
  _state.sent();
1743
+ if (this.isStale(epoch, generation)) return [
1744
+ 2,
1745
+ true
1746
+ ];
1670
1747
  this.timing.startAdRequestWatchdog(requestToken);
1671
- this.timing.noteAdRequestSent();
1672
- this.beginFunnelRequest(adPlayer, requestToken);
1673
1748
  return [
1674
1749
  4,
1675
1750
  this.callController(function() {
@@ -1679,7 +1754,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1679
1754
  case 3:
1680
1755
  _state.sent();
1681
1756
  this.timing.clearAdRequestWatchdog();
1682
- if (this.timing.activeAdRequestToken !== requestToken) {
1757
+ if (this.isStale(epoch, generation)) {
1758
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
1759
+ requestId: requestToken
1760
+ });
1683
1761
  return [
1684
1762
  2,
1685
1763
  true
@@ -1687,11 +1765,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1687
1765
  }
1688
1766
  podCount = (_ref = (_adPlayer_getPodAdCount = adPlayer.getPodAdCount) === null || _adPlayer_getPodAdCount === void 0 ? void 0 : _adPlayer_getPodAdCount.call(adPlayer)) !== null && _ref !== void 0 ? _ref : 1;
1689
1767
  if (podCount < 1) {
1768
+ if (this.timing.activeAdRequestToken === requestToken) {
1769
+ this.timing.activeAdRequestToken = null;
1770
+ }
1771
+ this.recordRequestFailure(new Error("No ads available"), podUrl);
1690
1772
  return [
1691
1773
  2,
1692
1774
  false
1693
1775
  ];
1694
1776
  }
1777
+ this.setSlotState("READY", "vast_ready");
1695
1778
  if (this.debug) {
1696
1779
  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"));
1697
1780
  }
@@ -1709,12 +1792,14 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1709
1792
  ];
1710
1793
  case 4:
1711
1794
  _state.sent();
1795
+ if (this.isStale(epoch, generation)) return [
1796
+ 2,
1797
+ true
1798
+ ];
1712
1799
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
1713
1800
  this.timing.scheduleAdStopAtBreakBoundary();
1714
1801
  }
1715
1802
  adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
1716
- this.continuousFetchingActive = true;
1717
- this.startContinuousFetching(baseVastUrl);
1718
1803
  return [
1719
1804
  2,
1720
1805
  true
@@ -1726,14 +1811,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1726
1811
  if (this.timing.activeAdRequestToken === requestToken) {
1727
1812
  this.timing.activeAdRequestToken = null;
1728
1813
  }
1814
+ if (this.isStale(epoch, generation)) {
1815
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
1816
+ requestId: requestToken,
1817
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1818
+ });
1819
+ return [
1820
+ 2,
1821
+ true
1822
+ ];
1823
+ }
1729
1824
  if (this.debug) {
1730
1825
  console.warn("[POD] Optimized pod request/play failed:", error);
1731
1826
  }
1732
- if (this.timing.isTemporaryAdError(error)) {
1733
- this.timing.temporaryFailureUrls.set(podUrl, Date.now());
1734
- }
1735
- this.continuousFetchingActive = true;
1736
- this.recreateAdController();
1827
+ this.recordRequestFailure(error, podUrl);
1737
1828
  return [
1738
1829
  2,
1739
1830
  false
@@ -1749,407 +1840,204 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
1749
1840
  },
1750
1841
  {
1751
1842
  // ───────────────────────────────────────────────────────────────
1752
- // Continuous fetching
1843
+ // Next-ad scheduling (single flight)
1753
1844
  // ───────────────────────────────────────────────────────────────
1754
- key: "startContinuousFetching",
1755
- value: function startContinuousFetching(baseVastUrl) {
1756
- if (!this.continuousFetchingActive) {
1757
- return;
1758
- }
1759
- if (this.continuousFetchLoopRunning) {
1760
- if (this.debug) {
1761
- console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start");
1762
- }
1763
- return;
1764
- }
1845
+ key: "setSlotState",
1846
+ value: function setSlotState(next, reason) {
1847
+ if (this.slotState === next) return;
1848
+ var previous = this.slotState;
1849
+ this.slotState = next;
1765
1850
  if (this.debug) {
1766
- console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop");
1851
+ console.log("[AdBreak][STATE] ".concat(previous, " -> ").concat(next), {
1852
+ reason: reason,
1853
+ breakId: this.timing.adBreakEpoch,
1854
+ requestId: this.currentRequestId,
1855
+ controllerId: this.controllerGeneration
1856
+ });
1767
1857
  }
1768
- this.continuousFetchLoopRunning = true;
1769
- this.continuousFetchLoop(baseVastUrl);
1770
1858
  }
1771
1859
  },
1772
1860
  {
1773
- key: "continuousFetchLoop",
1774
- value: function continuousFetchLoop(baseVastUrl) {
1775
- return _async_to_generator(function() {
1776
- var _this, _loop, epoch, _ret;
1777
- return _ts_generator(this, function(_state) {
1778
- switch(_state.label){
1779
- case 0:
1780
- _loop = function() {
1781
- var remaining, maxQueueSize, newAdUrl, queuedUrlsPreview, generationDelay;
1782
- return _ts_generator(this, function(_state) {
1783
- switch(_state.label){
1784
- case 0:
1785
- remaining = Math.min(_this.timing.getWallClockRemainingAdMs(), _this.timing.getDurationBudgetRemainingMs());
1786
- if (remaining <= _this.timing.getMinRemainingMsToStartAd()) {
1787
- if (_this.debug) {
1788
- 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"));
1789
- }
1790
- return [
1791
- 2,
1792
- "break"
1793
- ];
1794
- }
1795
- if (_this.timing.isGamInCooldown()) {
1796
- if (_this.debug) {
1797
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation");
1798
- }
1799
- return [
1800
- 2,
1801
- "break"
1802
- ];
1803
- }
1804
- if (_this.timing.consecutiveFailures >= _this.timing.maxConsecutiveFailures) {
1805
- if (_this.debug) {
1806
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(_this.timing.consecutiveFailures, "), stopping URL generation"));
1807
- }
1808
- return [
1809
- 2,
1810
- "break"
1811
- ];
1812
- }
1813
- if (_this.timing.totalAdRequestsInBreak >= _this.timing.maxTotalAdRequestsPerBreak) {
1814
- if (_this.debug) {
1815
- console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(_this.timing.maxTotalAdRequestsPerBreak, "), stopping"));
1816
- }
1817
- return [
1818
- 2,
1819
- "break"
1820
- ];
1821
- }
1822
- maxQueueSize = 5;
1823
- if (!(_this.adRequestQueue.length >= maxQueueSize)) return [
1824
- 3,
1825
- 2
1826
- ];
1827
- if (_this.debug) {
1828
- console.log("[CONTINUOUS-FETCH] URL queue full (".concat(_this.adRequestQueue.length, "), waiting..."));
1829
- }
1830
- return [
1831
- 4,
1832
- new Promise(function(resolve) {
1833
- return setTimeout(resolve, 1e3);
1834
- })
1835
- ];
1836
- case 1:
1837
- _state.sent();
1838
- return [
1839
- 2,
1840
- "continue"
1841
- ];
1842
- case 2:
1843
- newAdUrl = _this.nextAdRequestUrl(baseVastUrl);
1844
- if (!(!newAdUrl || _this.timing.failedVastUrls.has(newAdUrl) || _this.timing.isUrlInCooldown(newAdUrl))) return [
1845
- 3,
1846
- 4
1847
- ];
1848
- return [
1849
- 4,
1850
- new Promise(function(resolve) {
1851
- return setTimeout(resolve, 500);
1852
- })
1853
- ];
1854
- case 3:
1855
- _state.sent();
1856
- return [
1857
- 2,
1858
- "continue"
1859
- ];
1860
- case 4:
1861
- if (_this.debug) {
1862
- queuedUrlsPreview = _to_consumable_array(_this.adRequestQueue).concat([
1863
- newAdUrl
1864
- ]);
1865
- console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(queuedUrlsPreview.length, ")"), {
1866
- queuedUrls: queuedUrlsPreview
1867
- });
1868
- }
1869
- _this.adRequestQueue.push(newAdUrl);
1870
- generationDelay = _this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, _this.timing.consecutiveFailures), 5e3) : 500;
1871
- return [
1872
- 4,
1873
- new Promise(function(resolve) {
1874
- return setTimeout(resolve, generationDelay);
1875
- })
1876
- ];
1877
- case 5:
1878
- _state.sent();
1879
- return [
1880
- 2
1881
- ];
1882
- }
1883
- });
1884
- };
1885
- epoch = this.timing.adBreakEpoch;
1886
- _state.label = 1;
1887
- case 1:
1888
- if (!(this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch)) return [
1889
- 3,
1890
- 3
1891
- ];
1892
- _this = this;
1893
- return [
1894
- 5,
1895
- _ts_values(_loop())
1896
- ];
1897
- case 2:
1898
- _ret = _state.sent();
1899
- if (_ret === "break") return [
1900
- 3,
1901
- 3
1902
- ];
1903
- return [
1904
- 3,
1905
- 1
1906
- ];
1907
- case 3:
1908
- this.continuousFetchLoopRunning = false;
1909
- if (this.debug) {
1910
- console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length, ")"), this.adRequestQueue.length > 0 ? {
1911
- queuedUrls: _to_consumable_array(this.adRequestQueue)
1912
- } : {});
1913
- }
1914
- return [
1915
- 2
1916
- ];
1917
- }
1918
- });
1919
- }).call(this);
1861
+ key: "isStale",
1862
+ value: function isStale(epoch, generation) {
1863
+ return !this.inAdBreak || epoch !== this.timing.adBreakEpoch || generation !== this.controllerGeneration;
1920
1864
  }
1921
1865
  },
1922
1866
  {
1923
- key: "stopContinuousFetching",
1924
- value: function stopContinuousFetching() {
1925
- this.continuousFetchingActive = false;
1926
- this.continuousFetchLoopRunning = false;
1927
- this.placeholder.hide();
1928
- if (this.debug) {
1929
- console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching");
1867
+ key: "getMinRemainingMsToRequestAd",
1868
+ value: function getMinRemainingMsToRequestAd() {
1869
+ var configured = this.host.config.minRemainingMsToRequestAd;
1870
+ var floor = this.timing.getMinRemainingMsToStartAd();
1871
+ if (typeof configured === "number" && configured >= 0) {
1872
+ return Math.max(configured, floor);
1930
1873
  }
1874
+ return Math.max(this.defaultMinRemainingMsToRequestAd, floor);
1931
1875
  }
1932
1876
  },
1933
1877
  {
1934
- key: "tryNextAvailableAdWithRateLimit",
1935
- value: // ───────────────────────────────────────────────────────────────
1936
- // Ad iteration
1937
- // ───────────────────────────────────────────────────────────────
1938
- function tryNextAvailableAdWithRateLimit() {
1939
- return _async_to_generator(function() {
1940
- var epoch, backoffMultiplier, backoffDelay, effectiveMinInterval, timeSinceLastRequest, waitTime;
1941
- return _ts_generator(this, function(_state) {
1942
- switch(_state.label){
1943
- case 0:
1944
- if (!this.inAdBreak) {
1945
- return [
1946
- 2
1947
- ];
1948
- }
1949
- epoch = this.timing.adBreakEpoch;
1950
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
1951
- if (this.debug) {
1952
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
1953
- }
1954
- this.handleAdPodComplete();
1955
- return [
1956
- 2
1957
- ];
1958
- }
1959
- backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);
1960
- backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);
1961
- effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);
1962
- timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;
1963
- if (!(timeSinceLastRequest < effectiveMinInterval)) return [
1964
- 3,
1965
- 2
1966
- ];
1967
- waitTime = effectiveMinInterval - timeSinceLastRequest;
1968
- if (this.debug) {
1969
- console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(waitTime, "ms before next request (backoff: ").concat(this.timing.consecutiveFailures, " failures)"));
1970
- }
1971
- return [
1972
- 4,
1973
- new Promise(function(resolve) {
1974
- return setTimeout(resolve, waitTime);
1975
- })
1976
- ];
1977
- case 1:
1978
- _state.sent();
1979
- _state.label = 2;
1980
- case 2:
1981
- if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {
1982
- return [
1983
- 2
1984
- ];
1985
- }
1986
- return [
1987
- 2,
1988
- this.tryNextAvailableAd(0)
1989
- ];
1990
- }
1878
+ key: "getMaxNoFillsPerBreak",
1879
+ value: function getMaxNoFillsPerBreak() {
1880
+ var configured = this.host.config.maxNoFillsPerBreak;
1881
+ return typeof configured === "number" && configured > 0 ? configured : this.defaultMaxNoFillsPerBreak;
1882
+ }
1883
+ },
1884
+ {
1885
+ key: "isBreakTimeBounded",
1886
+ value: function isBreakTimeBounded() {
1887
+ return this.breakSource === "scte35" || this.timing.expectedAdBreakDurationMs != null;
1888
+ }
1889
+ },
1890
+ {
1891
+ key: "getStopRequestingReason",
1892
+ value: function getStopRequestingReason(remainingMs) {
1893
+ if (this.breakSource === "vmap") {
1894
+ if (this.adPodQueue.length === 0) return "vmap_queue_empty";
1895
+ } else if (this.breakSource !== "scte35" || !this.followUpBaseVastUrl) {
1896
+ return "no_follow_up_source";
1897
+ }
1898
+ if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
1899
+ return "max_consecutive_failures";
1900
+ }
1901
+ if (this.unusableResponsesInBreak >= this.getMaxNoFillsPerBreak()) {
1902
+ return "unusable_response_limit";
1903
+ }
1904
+ if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {
1905
+ return "request_cap";
1906
+ }
1907
+ if (this.timing.isGamInCooldown()) {
1908
+ return "gam_cooldown";
1909
+ }
1910
+ if (this.isBreakTimeBounded() && remainingMs < this.getMinRemainingMsToRequestAd()) {
1911
+ return "insufficient_break_time";
1912
+ }
1913
+ return void 0;
1914
+ }
1915
+ },
1916
+ {
1917
+ key: "getNextRequestDelayMs",
1918
+ value: function getNextRequestDelayMs() {
1919
+ var failures = this.timing.consecutiveFailures;
1920
+ var backoff = failures > 0 ? Math.min(this.timing.backoffBaseMs * Math.pow(2, failures), this.timing.maxBackoffMs) : 0;
1921
+ var minInterval = this.timing.minAdRequestIntervalMs + backoff;
1922
+ var sinceLast = Date.now() - this.timing.lastAdRequestTime;
1923
+ return Math.max(0, minInterval - sinceLast);
1924
+ }
1925
+ },
1926
+ {
1927
+ key: "requestNextAd",
1928
+ value: function requestNextAd(trigger) {
1929
+ var _this = this;
1930
+ if (!this.inAdBreak) return;
1931
+ if (this.slotState !== "NEEDS_NEXT_AD") {
1932
+ this.logOrchestratorFunnel("request_suppressed", {
1933
+ trigger: trigger,
1934
+ state: this.slotState,
1935
+ why: "slot_busy"
1991
1936
  });
1992
- }).call(this);
1937
+ return;
1938
+ }
1939
+ if (this.nextAdTimerId != null) {
1940
+ this.logOrchestratorFunnel("request_suppressed", {
1941
+ trigger: trigger,
1942
+ state: this.slotState,
1943
+ why: "request_already_scheduled"
1944
+ });
1945
+ return;
1946
+ }
1947
+ var remainingMs = this.timing.getRemainingAdMs();
1948
+ var stopReason = this.getStopRequestingReason(remainingMs);
1949
+ if (stopReason) {
1950
+ this.logOrchestratorFunnel("next_ad_decision", {
1951
+ trigger: trigger,
1952
+ decision: "end_break",
1953
+ reason: stopReason,
1954
+ remainingMs: remainingMs,
1955
+ requestsSent: this.timing.totalAdRequestsInBreak,
1956
+ unusableResponses: this.unusableResponsesInBreak,
1957
+ consecutiveFailures: this.timing.consecutiveFailures
1958
+ });
1959
+ this.handleAdPodComplete(stopReason);
1960
+ return;
1961
+ }
1962
+ var waitMs = this.getNextRequestDelayMs();
1963
+ if (waitMs > 0 && this.isBreakTimeBounded() && remainingMs - waitMs < this.getMinRemainingMsToRequestAd()) {
1964
+ this.logOrchestratorFunnel("next_ad_decision", {
1965
+ trigger: trigger,
1966
+ decision: "end_break",
1967
+ reason: "insufficient_break_time_after_backoff",
1968
+ remainingMs: remainingMs,
1969
+ waitMs: waitMs
1970
+ });
1971
+ this.handleAdPodComplete("insufficient_break_time_after_backoff");
1972
+ return;
1973
+ }
1974
+ this.logOrchestratorFunnel("next_ad_decision", {
1975
+ trigger: trigger,
1976
+ decision: waitMs > 0 ? "request_after_delay" : "request_now",
1977
+ waitMs: waitMs,
1978
+ remainingMs: remainingMs,
1979
+ consecutiveFailures: this.timing.consecutiveFailures
1980
+ });
1981
+ if (waitMs > 0) {
1982
+ if (!this.isShowingPlaceholder) {
1983
+ this.isShowingPlaceholder = true;
1984
+ this.host.getAdPlayer().showPlaceholder();
1985
+ }
1986
+ var epoch = this.timing.adBreakEpoch;
1987
+ this.nextAdTimerId = window.setTimeout(function() {
1988
+ _this.nextAdTimerId = void 0;
1989
+ if (!_this.inAdBreak || epoch !== _this.timing.adBreakEpoch) return;
1990
+ _this.requestNextAd("".concat(trigger, ":after_delay"));
1991
+ }, waitMs);
1992
+ return;
1993
+ }
1994
+ void this.requestFollowUpAd(trigger);
1993
1995
  }
1994
1996
  },
1995
1997
  {
1996
- key: "tryNextAvailableAd",
1997
- value: function tryNextAvailableAd() {
1998
- var retryCount = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
1998
+ key: "requestFollowUpAd",
1999
+ value: function requestFollowUpAd(trigger) {
1999
2000
  return _async_to_generator(function() {
2000
- var remaining, nextAdUrl, error, errorMessage, maxRetries;
2001
+ var url, epoch, unused;
2001
2002
  return _ts_generator(this, function(_state) {
2002
2003
  switch(_state.label){
2003
2004
  case 0:
2004
- if (!this.inAdBreak) {
2005
- return [
2006
- 2
2007
- ];
2008
- }
2009
- remaining = this.timing.getRemainingAdMs();
2010
- if (!this.timing.hasTimeToStartAnotherAd()) {
2011
- if (this.debug) {
2012
- console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(remaining, "ms) to start another ad, ending ad break"));
2013
- }
2014
- this.handleAdPodComplete();
2015
- return [
2016
- 2
2017
- ];
2018
- }
2019
- if (this.timing.isGamInCooldown()) {
2020
- if (this.debug) {
2021
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully");
2022
- }
2023
- this.handleAdPodComplete();
2024
- return [
2025
- 2
2026
- ];
2027
- }
2028
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
2029
- if (this.debug) {
2030
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break"));
2031
- }
2032
- this.handleAdPodComplete();
2033
- return [
2034
- 2
2035
- ];
2005
+ if (this.breakSource === "vmap") {
2006
+ url = this.adPodQueue.shift();
2007
+ } else if (this.followUpBaseVastUrl) {
2008
+ url = this.nextAdRequestUrl(this.followUpBaseVastUrl);
2036
2009
  }
2037
- this.timing.cleanupTemporaryFailures();
2010
+ if (!url) return [
2011
+ 2
2012
+ ];
2013
+ this.noteVastUrlGenerated(ensureVideoAdType(url), trigger);
2014
+ epoch = this.timing.adBreakEpoch;
2038
2015
  _state.label = 1;
2039
2016
  case 1:
2040
- if (!(this.adRequestQueue.length > 0)) return [
2041
- 3,
2042
- 9
2043
- ];
2044
- nextAdUrl = this.adRequestQueue.shift();
2045
- if (!nextAdUrl) return [
2046
- 3,
2047
- 1
2048
- ];
2049
- if (this.timing.failedVastUrls.has(nextAdUrl)) {
2050
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...");
2051
- return [
2052
- 3,
2053
- 1
2054
- ];
2055
- }
2056
- if (this.timing.isUrlInCooldown(nextAdUrl)) {
2057
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...");
2058
- return [
2059
- 3,
2060
- 1
2061
- ];
2062
- }
2063
- if (this.debug) {
2064
- console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex + 1, ", ").concat(this.adRequestQueue.length, " remaining in queue)"));
2065
- }
2066
- _state.label = 2;
2067
- case 2:
2068
2017
  _state.trys.push([
2069
- 2,
2070
- 4,
2018
+ 1,
2019
+ 3,
2071
2020
  ,
2072
- 8
2021
+ 4
2073
2022
  ]);
2074
2023
  return [
2075
2024
  4,
2076
- this.playSingleAd(nextAdUrl)
2077
- ];
2078
- case 3:
2079
- _state.sent();
2080
- return [
2081
- 3,
2082
- 8
2083
- ];
2084
- case 4:
2085
- error = _state.sent();
2086
- errorMessage = error.message;
2087
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad request failed:", errorMessage);
2088
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
2089
- 3,
2090
- 6
2091
- ];
2092
- this.timing.consecutiveFailures++;
2093
- return [
2094
- 4,
2095
- this.tryNextAvailableAdWithRateLimit()
2096
- ];
2097
- case 5:
2098
- _state.sent();
2099
- return [
2100
- 2
2101
- ];
2102
- case 6:
2103
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
2104
- this.timing.consecutiveFailures++;
2105
- }
2106
- return [
2107
- 4,
2108
- this.tryNextAvailableAdWithRateLimit()
2025
+ this.playSingleAd(url, trigger)
2109
2026
  ];
2110
- case 7:
2027
+ case 2:
2111
2028
  _state.sent();
2112
2029
  return [
2113
2030
  3,
2114
- 8
2031
+ 4
2115
2032
  ];
2116
- case 8:
2033
+ case 3:
2034
+ unused = _state.sent();
2035
+ this.continueAfterRequestFailure(epoch);
2117
2036
  return [
2118
- 2
2119
- ];
2120
- case 9:
2121
- maxRetries = 3;
2122
- if (!(this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3)) return [
2123
2037
  3,
2124
- 12
2125
- ];
2126
- if (this.debug) {
2127
- console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(retryCount + 1, "/").concat(maxRetries, ")"));
2128
- }
2129
- return [
2130
- 4,
2131
- new Promise(function(resolve) {
2132
- return setTimeout(resolve, 500);
2133
- })
2134
- ];
2135
- case 10:
2136
- _state.sent();
2137
- return [
2138
- 4,
2139
- this.tryNextAvailableAd(retryCount + 1)
2140
- ];
2141
- case 11:
2142
- _state.sent();
2143
- return [
2144
- 2
2038
+ 4
2145
2039
  ];
2146
- case 12:
2147
- if (!this.isShowingPlaceholder && remaining > 1e3) {
2148
- this.showPlaceholderAndWaitForAds();
2149
- } else {
2150
- if (this.debug) console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break");
2151
- this.handleAdPodComplete();
2152
- }
2040
+ case 4:
2153
2041
  return [
2154
2042
  2
2155
2043
  ];
@@ -2158,12 +2046,168 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2158
2046
  }).call(this);
2159
2047
  }
2160
2048
  },
2049
+ {
2050
+ key: "continueAfterRequestFailure",
2051
+ value: function continueAfterRequestFailure() {
2052
+ var epoch = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.timing.adBreakEpoch;
2053
+ if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) return;
2054
+ this.setSlotState("NEEDS_NEXT_AD", "request_failed");
2055
+ this.requestNextAd("after_failure");
2056
+ }
2057
+ },
2058
+ {
2059
+ key: "cancelScheduledRequest",
2060
+ value: function cancelScheduledRequest() {
2061
+ if (this.nextAdTimerId != null) {
2062
+ clearTimeout(this.nextAdTimerId);
2063
+ this.nextAdTimerId = void 0;
2064
+ }
2065
+ }
2066
+ },
2067
+ {
2068
+ key: "noteVastUrlGenerated",
2069
+ value: function noteVastUrlGenerated(url, source) {
2070
+ var _ref, _ref1, _ref2, _ref3, _ref4;
2071
+ var params;
2072
+ try {
2073
+ params = new URL(url).searchParams;
2074
+ } catch (unused) {}
2075
+ var adType = (_ref = params === null || params === void 0 ? void 0 : params.get("ad_type")) !== null && _ref !== void 0 ? _ref : void 0;
2076
+ this.logOrchestratorFunnel("vast_url_generated", {
2077
+ source: source,
2078
+ pod: (_ref1 = params === null || params === void 0 ? void 0 : params.get("pod")) !== null && _ref1 !== void 0 ? _ref1 : void 0,
2079
+ pmad: (_ref2 = params === null || params === void 0 ? void 0 : params.get("pmad")) !== null && _ref2 !== void 0 ? _ref2 : void 0,
2080
+ pmnd: (_ref3 = params === null || params === void 0 ? void 0 : params.get("pmnd")) !== null && _ref3 !== void 0 ? _ref3 : void 0,
2081
+ pmxd: (_ref4 = params === null || params === void 0 ? void 0 : params.get("pmxd")) !== null && _ref4 !== void 0 ? _ref4 : void 0,
2082
+ adType: adType
2083
+ });
2084
+ if (adType === "audio" || adType === "audio_video") {
2085
+ console.warn("[AdBreak] VAST tag requests ad_type=".concat(adType, "; GAM may return audio-only creatives, which this video player rejects"));
2086
+ this.countFunnelStage("tag_allows_audio");
2087
+ }
2088
+ }
2089
+ },
2090
+ {
2091
+ key: "recordRequestFailure",
2092
+ value: function recordRequestFailure(error, vastTagUrl) {
2093
+ var _diag_vastAdCount;
2094
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
2095
+ var message = (error === null || error === void 0 ? void 0 : error.message) || "";
2096
+ var outcome;
2097
+ if (message.includes("ad_duration_exceeds_budget")) {
2098
+ outcome = "discarded_budget";
2099
+ } else if (message.includes("VAST fill rejected")) {
2100
+ outcome = "fill_rejected";
2101
+ } else if (/no ads available|no fill|nofill/i.test(message)) {
2102
+ outcome = "no_fill";
2103
+ } else if (/timeout/i.test(message)) {
2104
+ outcome = "request_timeout";
2105
+ } else if (/destroyed|aborted/i.test(message)) {
2106
+ outcome = "request_aborted";
2107
+ } else if (diag && ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired) {
2108
+ outcome = "playback_failed";
2109
+ } else {
2110
+ outcome = "request_failed";
2111
+ }
2112
+ this.timing.consecutiveFailures++;
2113
+ if (outcome === "no_fill" || outcome === "fill_rejected" || outcome === "discarded_budget") {
2114
+ this.unusableResponsesInBreak++;
2115
+ }
2116
+ if (outcome === "no_fill") {
2117
+ this.timing.recordGamNoFill();
2118
+ }
2119
+ if (diag && !diag.failureReason) {
2120
+ diag.failureReason = "".concat(outcome, ": ").concat(message);
2121
+ }
2122
+ if (this.timing.isTemporaryAdError(error)) {
2123
+ this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
2124
+ } else if (outcome !== "discarded_budget") {
2125
+ this.timing.failedVastUrls.add(vastTagUrl);
2126
+ }
2127
+ this.countFunnelStage("request_outcome:".concat(outcome));
2128
+ this.logOrchestratorFunnel("request_outcome", {
2129
+ outcome: outcome,
2130
+ errorMessage: message,
2131
+ consecutiveFailures: this.timing.consecutiveFailures,
2132
+ unusableResponsesInBreak: this.unusableResponsesInBreak
2133
+ });
2134
+ }
2135
+ },
2136
+ {
2137
+ // ───────────────────────────────────────────────────────────────
2138
+ // Per-request diagnostics
2139
+ // ───────────────────────────────────────────────────────────────
2140
+ key: "recordRequestDiagnostic",
2141
+ value: function recordRequestDiagnostic(payload) {
2142
+ var requestId = payload.requestId;
2143
+ if (typeof requestId !== "number") return;
2144
+ var diag = this.requestDiagnostics.get(requestId);
2145
+ if (!diag) return;
2146
+ switch(payload.stage){
2147
+ case "gam_http_request_sent":
2148
+ diag.gamRequestSent++;
2149
+ break;
2150
+ case "gam_response_received":
2151
+ diag.vastHttpStatus = payload.httpStatus;
2152
+ break;
2153
+ case "vast_parsed":
2154
+ diag.vastAdCount = payload.adElementCount;
2155
+ break;
2156
+ case "wrapper_fetch":
2157
+ case "inline_resolved":
2158
+ if (typeof payload.depth === "number") {
2159
+ diag.wrapperDepth = Math.max(diag.wrapperDepth, payload.depth);
2160
+ }
2161
+ if (payload.stage === "inline_resolved") diag.inlineResolved = true;
2162
+ break;
2163
+ case "mediafile_evaluated":
2164
+ diag.mediaCandidateCount++;
2165
+ if (payload.whyAccepted) diag.supportedMediaCount++;
2166
+ break;
2167
+ case "playing":
2168
+ diag.playStarted = true;
2169
+ break;
2170
+ case "impression_fired":
2171
+ diag.impressionFired = true;
2172
+ break;
2173
+ default:
2174
+ if (REQUEST_FAILURE_STAGES.has(payload.stage) && !diag.failureReason) {
2175
+ diag.failureReason = payload.reason ? "".concat(payload.stage, ":").concat(payload.reason) : payload.stage;
2176
+ }
2177
+ }
2178
+ }
2179
+ },
2180
+ {
2181
+ key: "finalizeRequestDiagnostics",
2182
+ value: function finalizeRequestDiagnostics(requestId, endReason) {
2183
+ var _diag_vastAdCount;
2184
+ if (requestId == null) return;
2185
+ var diag = this.requestDiagnostics.get(requestId);
2186
+ if (!diag) return;
2187
+ this.requestDiagnostics.delete(requestId);
2188
+ if (!diag.impressionFired && !diag.failureReason && endReason) {
2189
+ diag.failureReason = endReason;
2190
+ }
2191
+ var gamReturnedAdWithoutImpression = ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired;
2192
+ if (gamReturnedAdWithoutImpression) {
2193
+ this.countFunnelStage("gam_ad_without_impression");
2194
+ }
2195
+ var startedAt = diag.startedAt, fields = _object_without_properties(diag, [
2196
+ "startedAt"
2197
+ ]);
2198
+ console.log("[AdBreak][REQUEST] summary", _object_spread_props(_object_spread({}, fields), {
2199
+ durationMs: Date.now() - startedAt,
2200
+ gamReturnedAdWithoutImpression: gamReturnedAdWithoutImpression
2201
+ }));
2202
+ }
2203
+ },
2161
2204
  {
2162
2205
  // ───────────────────────────────────────────────────────────────
2163
2206
  // Single ad playback
2164
2207
  // ───────────────────────────────────────────────────────────────
2165
2208
  key: "withCurrentPodBudget",
2166
- value: function withCurrentPodBudget(vastTagUrl) {
2209
+ value: function withCurrentPodBudget(rawVastTagUrl) {
2210
+ var vastTagUrl = ensureVideoAdType(rawVastTagUrl);
2167
2211
  var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
2168
2212
  if (!(remaining > 0)) return vastTagUrl;
2169
2213
  try {
@@ -2222,18 +2266,34 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2222
2266
  },
2223
2267
  {
2224
2268
  key: "beginFunnelRequest",
2225
- value: function beginFunnelRequest(adPlayer, requestToken) {
2269
+ value: function beginFunnelRequest(adPlayer, requestToken, trigger) {
2226
2270
  var _adPlayer_setFunnelContext;
2227
2271
  if (this.controllerCallInFlight) {
2228
2272
  this.logOrchestratorFunnel("duplicate_request_detected", {
2229
2273
  newRequestId: requestToken
2230
2274
  });
2231
2275
  }
2276
+ this.finalizeRequestDiagnostics(this.currentRequestId);
2232
2277
  this.currentRequestId = requestToken;
2233
2278
  this.requestStartedAt = Date.now();
2279
+ this.requestDiagnostics.set(requestToken, {
2280
+ breakId: this.timing.adBreakEpoch,
2281
+ requestId: requestToken,
2282
+ controllerId: this.controllerGeneration,
2283
+ trigger: trigger,
2284
+ gamRequestSent: 0,
2285
+ wrapperDepth: 0,
2286
+ inlineResolved: false,
2287
+ mediaCandidateCount: 0,
2288
+ supportedMediaCount: 0,
2289
+ playStarted: false,
2290
+ impressionFired: false,
2291
+ startedAt: Date.now()
2292
+ });
2234
2293
  (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
2235
2294
  breakId: this.timing.adBreakEpoch,
2236
- requestId: requestToken
2295
+ requestId: requestToken,
2296
+ controllerId: this.controllerGeneration
2237
2297
  });
2238
2298
  }
2239
2299
  },
@@ -2264,7 +2324,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2264
2324
  adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
2265
2325
  return;
2266
2326
  }
2267
- this.handleAdFailure();
2327
+ this.handleAdFailure("request_watchdog_timeout");
2268
2328
  }
2269
2329
  },
2270
2330
  {
@@ -2310,21 +2370,30 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2310
2370
  {
2311
2371
  key: "playSingleAd",
2312
2372
  value: function playSingleAd(vastTagUrl) {
2373
+ var trigger = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "vmap";
2313
2374
  return _async_to_generator(function() {
2314
- var adPlayer, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, playError, error, errorMessage;
2375
+ var epoch, generation, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, error;
2315
2376
  return _ts_generator(this, function(_state) {
2316
2377
  switch(_state.label){
2317
2378
  case 0:
2318
- adPlayer = this.host.getAdPlayer();
2319
- if (adPlayer.isAdPlaying()) return [
2320
- 2
2321
- ];
2379
+ if (this.slotState === "REQUESTING" || this.slotState === "READY" || this.slotState === "PLAYING" || this.slotState === "ENDING") {
2380
+ this.logOrchestratorFunnel("request_suppressed", {
2381
+ trigger: trigger,
2382
+ state: this.slotState,
2383
+ why: "request_in_flight"
2384
+ });
2385
+ return [
2386
+ 2
2387
+ ];
2388
+ }
2322
2389
  if (this.timing.failedVastUrls.has(vastTagUrl)) {
2323
2390
  if (this.debug) console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:", vastTagUrl);
2391
+ this.timing.consecutiveFailures++;
2324
2392
  throw new Error("VAST URL permanently failed");
2325
2393
  }
2326
2394
  if (this.timing.isUrlInCooldown(vastTagUrl)) {
2327
2395
  if (this.debug) console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):", vastTagUrl);
2396
+ this.timing.consecutiveFailures++;
2328
2397
  throw new Error("VAST URL in cooldown after no-fill");
2329
2398
  }
2330
2399
  if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
@@ -2335,16 +2404,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2335
2404
  if (this.debug) console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request");
2336
2405
  throw new Error("GAM in cooldown");
2337
2406
  }
2338
- this.recreateAdController();
2407
+ epoch = this.timing.adBreakEpoch;
2408
+ this.recreateAdController("new_request");
2409
+ generation = this.controllerGeneration;
2339
2410
  requestToken = ++this.timing.adRequestTokenCounter;
2340
2411
  this.timing.activeAdRequestToken = requestToken;
2412
+ ap = this.host.getAdPlayer();
2413
+ requestUrl = this.withCurrentPodBudget(vastTagUrl);
2414
+ this.currentVastUrl = requestUrl;
2415
+ this.setSlotState("REQUESTING", trigger);
2416
+ this.beginFunnelRequest(ap, requestToken, trigger);
2341
2417
  _state.label = 1;
2342
2418
  case 1:
2343
2419
  _state.trys.push([
2344
2420
  1,
2345
- 8,
2421
+ 5,
2346
2422
  ,
2347
- 9
2423
+ 6
2348
2424
  ]);
2349
2425
  return [
2350
2426
  4,
@@ -2352,12 +2428,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2352
2428
  ];
2353
2429
  case 2:
2354
2430
  _state.sent();
2431
+ if (this.isStale(epoch, generation)) return [
2432
+ 2
2433
+ ];
2355
2434
  this.timing.startAdRequestWatchdog(requestToken);
2356
- this.timing.noteAdRequestSent();
2357
- ap = this.host.getAdPlayer();
2358
- requestUrl = this.withCurrentPodBudget(vastTagUrl);
2359
- this.currentVastUrl = requestUrl;
2360
- this.beginFunnelRequest(ap, requestToken);
2361
2435
  return [
2362
2436
  4,
2363
2437
  this.callController(function() {
@@ -2366,36 +2440,31 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2366
2440
  ];
2367
2441
  case 3:
2368
2442
  _state.sent();
2443
+ this.timing.clearAdRequestWatchdog();
2444
+ if (this.isStale(epoch, generation)) {
2445
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
2446
+ requestId: requestToken
2447
+ });
2448
+ return [
2449
+ 2
2450
+ ];
2451
+ }
2369
2452
  sendAdLoadedTracking(this.host.config.licenseKey, {
2370
2453
  source: "hls",
2371
2454
  vastUrl: requestUrl,
2372
2455
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2373
2456
  }, this.analyticsContext).catch(function() {});
2374
- this.timing.clearAdRequestWatchdog();
2375
- if (this.timing.activeAdRequestToken !== requestToken) return [
2376
- 2
2377
- ];
2378
2457
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
2379
2458
  ;
2380
2459
  adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
2381
2460
  remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
2382
2461
  this.logOrchestratorFunnel("discarded_budget", {
2383
- vastUrl: requestUrl,
2384
2462
  adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
2385
2463
  remainingMs: remainingMs
2386
2464
  });
2387
- this.timing.rejectLoadedAdForDuration(ap);
2388
- this.recreateAdController();
2389
2465
  throw new Error("ad_duration_exceeds_budget");
2390
2466
  }
2391
- _state.label = 4;
2392
- case 4:
2393
- _state.trys.push([
2394
- 4,
2395
- 6,
2396
- ,
2397
- 7
2398
- ]);
2467
+ this.setSlotState("READY", "vast_ready");
2399
2468
  this.timing.startAdFailsafeTimer(requestToken);
2400
2469
  return [
2401
2470
  4,
@@ -2403,8 +2472,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2403
2472
  return ap.play();
2404
2473
  })
2405
2474
  ];
2406
- case 5:
2475
+ case 4:
2407
2476
  _state.sent();
2477
+ if (this.isStale(epoch, generation)) return [
2478
+ 2
2479
+ ];
2408
2480
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
2409
2481
  this.timing.scheduleAdStopAtBreakBoundary();
2410
2482
  }
@@ -2412,216 +2484,31 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2412
2484
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
2413
2485
  return [
2414
2486
  3,
2415
- 7
2416
- ];
2417
- case 6:
2418
- playError = _state.sent();
2419
- if (this.debug) console.error("[AD-ERROR] Failed to play ad:", playError);
2420
- if (this.timing.isTemporaryAdError(playError)) {
2421
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
2422
- if (this.debug) console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown");
2423
- } else {
2424
- this.timing.failedVastUrls.add(vastTagUrl);
2425
- if (this.debug) console.log("[AD-ERROR] Permanent play error - URL blacklisted");
2426
- }
2427
- this.timing.clearAdFailsafeTimer();
2428
- if (this.timing.activeAdRequestToken === requestToken) {
2429
- this.timing.activeAdRequestToken = null;
2430
- }
2431
- throw playError;
2432
- case 7:
2433
- return [
2434
- 3,
2435
- 9
2487
+ 6
2436
2488
  ];
2437
- case 8:
2489
+ case 5:
2438
2490
  error = _state.sent();
2439
- errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "";
2440
- if (this.debug) console.error("[AD-ERROR] Ad request failed:", errorMessage);
2441
- if (this.timing.isTemporaryAdError(error)) {
2442
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
2443
- if (this.debug) console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown");
2444
- } else {
2445
- this.timing.failedVastUrls.add(vastTagUrl);
2446
- if (this.debug) console.log("[AD-ERROR] Permanent error - URL blacklisted:", errorMessage);
2447
- }
2448
2491
  this.timing.clearAdRequestWatchdog();
2449
2492
  this.timing.clearAdFailsafeTimer();
2450
2493
  if (this.timing.activeAdRequestToken === requestToken) {
2451
2494
  this.timing.activeAdRequestToken = null;
2452
2495
  }
2453
- throw error;
2454
- case 9:
2455
- return [
2456
- 2
2457
- ];
2458
- }
2459
- });
2460
- }).call(this);
2461
- }
2462
- },
2463
- {
2464
- key: "showPlaceholderAndWaitForAds",
2465
- value: // ───────────────────────────────────────────────────────────────
2466
- // Placeholder wait
2467
- // ───────────────────────────────────────────────────────────────
2468
- function showPlaceholderAndWaitForAds() {
2469
- return _async_to_generator(function() {
2470
- var remaining, waitTime, checkInterval, maxChecks, i, nextAdUrl, error, errorMessage;
2471
- return _ts_generator(this, function(_state) {
2472
- switch(_state.label){
2473
- case 0:
2474
- remaining = this.timing.getRemainingAdMs();
2475
- waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);
2476
- if (this.timing.isGamInCooldown()) {
2477
- if (this.debug) console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait");
2478
- this.handleAdPodComplete();
2479
- return [
2480
- 2
2481
- ];
2482
- }
2483
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
2484
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures");
2485
- this.handleAdPodComplete();
2486
- return [
2487
- 2
2488
- ];
2489
- }
2490
- if (waitTime < 1e3) {
2491
- this.handleAdPodComplete();
2496
+ if (this.isStale(epoch, generation)) {
2497
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
2498
+ requestId: requestToken,
2499
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2500
+ });
2492
2501
  return [
2493
2502
  2
2494
2503
  ];
2495
2504
  }
2496
- if (this.debug) {
2497
- console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(waitTime, "ms while waiting for ad URLs"));
2498
- }
2499
- this.isShowingPlaceholder = true;
2500
- this.host.getAdPlayer().showPlaceholder();
2501
- checkInterval = 300;
2502
- maxChecks = Math.floor(waitTime / checkInterval);
2503
- i = 0;
2504
- _state.label = 1;
2505
- case 1:
2506
- if (!(i < maxChecks)) return [
2507
- 3,
2508
- 12
2509
- ];
2510
- return [
2511
- 4,
2512
- new Promise(function(resolve) {
2513
- return setTimeout(resolve, checkInterval);
2514
- })
2515
- ];
2516
- case 2:
2517
- _state.sent();
2518
- if (!this.inAdBreak) return [
2519
- 2
2520
- ];
2521
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
2522
- if (this.debug) console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait");
2523
- return [
2524
- 3,
2525
- 12
2526
- ];
2527
- }
2528
- if (!this.timing.hasTimeToStartAnotherAd()) {
2529
- if (this.debug) console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break");
2530
- return [
2531
- 3,
2532
- 12
2533
- ];
2505
+ if (this.debug) console.error("[AD-ERROR] Ad request failed:", error === null || error === void 0 ? void 0 : error.message);
2506
+ this.recordRequestFailure(error, vastTagUrl);
2507
+ if ((error === null || error === void 0 ? void 0 : error.message) === "ad_duration_exceeds_budget") {
2508
+ this.recreateAdController("discarded_budget");
2534
2509
  }
2535
- _state.label = 3;
2536
- case 3:
2537
- if (!(this.adRequestQueue.length > 0)) return [
2538
- 3,
2539
- 11
2540
- ];
2541
- if (!this.timing.hasTimeToStartAnotherAd()) return [
2542
- 3,
2543
- 11
2544
- ];
2545
- nextAdUrl = this.adRequestQueue.shift();
2546
- if (!nextAdUrl) return [
2547
- 3,
2548
- 3
2549
- ];
2550
- if (this.timing.failedVastUrls.has(nextAdUrl)) return [
2551
- 3,
2552
- 3
2553
- ];
2554
- if (this.timing.isUrlInCooldown(nextAdUrl)) return [
2555
- 3,
2556
- 3
2557
- ];
2558
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player");
2559
- this.isShowingPlaceholder = false;
2560
- this.host.getAdPlayer().hidePlaceholder();
2561
- _state.label = 4;
2562
- case 4:
2563
- _state.trys.push([
2564
- 4,
2565
- 6,
2566
- ,
2567
- 10
2568
- ]);
2569
- return [
2570
- 4,
2571
- this.playSingleAd(nextAdUrl)
2572
- ];
2573
- case 5:
2574
- _state.sent();
2575
- return [
2576
- 3,
2577
- 10
2578
- ];
2510
+ throw error;
2579
2511
  case 6:
2580
- error = _state.sent();
2581
- errorMessage = error.message;
2582
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
2583
- 3,
2584
- 8
2585
- ];
2586
- this.timing.consecutiveFailures++;
2587
- return [
2588
- 4,
2589
- this.tryNextAvailableAdWithRateLimit()
2590
- ];
2591
- case 7:
2592
- _state.sent();
2593
- return [
2594
- 2
2595
- ];
2596
- case 8:
2597
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
2598
- this.timing.consecutiveFailures++;
2599
- }
2600
- return [
2601
- 4,
2602
- this.tryNextAvailableAdWithRateLimit()
2603
- ];
2604
- case 9:
2605
- _state.sent();
2606
- return [
2607
- 3,
2608
- 10
2609
- ];
2610
- case 10:
2611
- return [
2612
- 2
2613
- ];
2614
- case 11:
2615
- i++;
2616
- return [
2617
- 3,
2618
- 1
2619
- ];
2620
- case 12:
2621
- if (this.debug) console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break");
2622
- this.isShowingPlaceholder = false;
2623
- this.host.getAdPlayer().hidePlaceholder();
2624
- this.handleAdPodComplete();
2625
2512
  return [
2626
2513
  2
2627
2514
  ];
@@ -2635,7 +2522,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2635
2522
  // Ad break completion
2636
2523
  // ───────────────────────────────────────────────────────────────
2637
2524
  key: "logBreakFunnel",
2638
- value: function logBreakFunnel() {
2525
+ value: function logBreakFunnel(endReason) {
2639
2526
  var funnel = this.breakFunnel;
2640
2527
  this.breakFunnel = {};
2641
2528
  if (Object.keys(funnel).length === 0) return;
@@ -2643,26 +2530,49 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2643
2530
  var _funnel_stage;
2644
2531
  return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
2645
2532
  };
2533
+ var countPrefix = function countPrefix(prefix) {
2534
+ return Object.keys(funnel).reduce(function(total, stage) {
2535
+ var _funnel_stage;
2536
+ return stage.indexOf(prefix) === 0 ? total + ((_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0) : total;
2537
+ }, 0);
2538
+ };
2646
2539
  var breakId = this.opportunityEpoch;
2647
- if (count("request_sent") > 0 && count("impression_fired") === 0) {
2540
+ var requestRetries = count("gam_http_request_retry");
2541
+ var requests = count("gam_http_request_sent") - requestRetries;
2542
+ if (requests > 0 && count("impression_fired") === 0) {
2648
2543
  console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
2649
2544
  breakId: breakId,
2650
- requests: count("request_sent")
2545
+ requests: requests,
2546
+ endReason: endReason
2651
2547
  });
2652
2548
  }
2653
2549
  console.log("[AdBreak][FUNNEL] Break summary", {
2654
2550
  breakId: breakId,
2551
+ endReason: endReason,
2655
2552
  opportunities: count("opportunity_created"),
2656
- requests: count("request_sent"),
2553
+ vastUrlsGenerated: count("vast_url_generated"),
2554
+ requests: requests,
2555
+ requestRetries: requestRetries,
2556
+ gamResponses: count("gam_response_received"),
2557
+ requestsSuppressed: count("request_suppressed"),
2657
2558
  duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
2658
2559
  filled: count("vast_received"),
2659
2560
  noFill: count("no_fill"),
2561
+ fillRejected: count("vast_fill_rejected"),
2562
+ gamAdWithoutImpression: count("gam_ad_without_impression"),
2563
+ playbackFailedAfterFill: count("request_outcome:playback_failed"),
2660
2564
  requestFailed: count("request_failed"),
2661
2565
  requestAbortedTimeout: count("request_aborted_timeout"),
2662
2566
  credentialsRetries: count("vast_credentials_retry"),
2663
2567
  wrapperFailures: count("wrapper_fetch:failure"),
2664
2568
  noSupportedMedia: count("vast_no_supported_media"),
2665
- vpaidOnly: count("vast_no_supported_media:vpaid_only"),
2569
+ vpaidOnly: count("vast_no_supported_media:vpaid"),
2570
+ audioOnly: count("vast_no_supported_media:audio_only"),
2571
+ mediaFilesEvaluated: count("mediafile_evaluated"),
2572
+ mediaFilesAccepted: count("mediafile_evaluated:accepted"),
2573
+ controllerDestroys: countPrefix("controller_destroy:"),
2574
+ staleCallbacks: count("stale_callback_ignored") + count("stale_request_result_ignored"),
2575
+ tagAllowsAudio: count("tag_allows_audio"),
2666
2576
  missingImpression: count("vast_missing_impression"),
2667
2577
  discardedBudget: count("discarded_budget"),
2668
2578
  mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
@@ -2697,25 +2607,50 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
2697
2607
  {
2698
2608
  key: "handleAdPodComplete",
2699
2609
  value: function handleAdPodComplete() {
2610
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "unspecified";
2700
2611
  if (this.debug) {
2701
- console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up");
2612
+ console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up", {
2613
+ reason: reason
2614
+ });
2615
+ }
2616
+ var previousState = this.slotState;
2617
+ var alreadyEnded = previousState === "IDLE" && !this.inAdBreak;
2618
+ this.setSlotState("ENDING", reason);
2619
+ this.cancelScheduledRequest();
2620
+ var adPlayer = this.host.getAdPlayer();
2621
+ if (previousState === "REQUESTING") {
2622
+ var _adPlayer_abortPendingRequest;
2623
+ (_adPlayer_abortPendingRequest = adPlayer.abortPendingRequest) === null || _adPlayer_abortPendingRequest === void 0 ? void 0 : _adPlayer_abortPendingRequest.call(adPlayer, "VAST request aborted: ad break ended (".concat(reason, ")"));
2702
2624
  }
2625
+ if (!alreadyEnded) {
2626
+ console.log("[AD-CONTROLLER] stop", {
2627
+ controllerId: this.controllerGeneration,
2628
+ requestId: this.currentRequestId,
2629
+ state: previousState,
2630
+ reason: reason
2631
+ });
2632
+ }
2633
+ this.finalizeRequestDiagnostics(this.currentRequestId, "break_ended:".concat(reason));
2634
+ this.currentRequestId = void 0;
2703
2635
  this.timing.resetForBreakEnd();
2704
- this.stopContinuousFetching();
2636
+ this.placeholder.hide();
2705
2637
  this.clearPendingAdBreak();
2706
2638
  if (this.isShowingPlaceholder) {
2707
- this.host.getAdPlayer().hidePlaceholder();
2639
+ adPlayer.hidePlaceholder();
2708
2640
  this.isShowingPlaceholder = false;
2709
2641
  }
2710
- this.adRequestQueue = [];
2711
2642
  this.inAdBreak = false;
2712
2643
  this.adDetectSentForCurrentBreak = false;
2713
2644
  this.cueManager.activeScte35BreakKey = void 0;
2714
2645
  this.cueManager.scheduledScte35BreakKey = void 0;
2715
2646
  this.adPodQueue = [];
2716
2647
  this.showAds = false;
2717
- this.host.getAdPlayer().stop().catch(function() {});
2718
- this.logBreakFunnel();
2648
+ this.breakSource = void 0;
2649
+ this.followUpBaseVastUrl = void 0;
2650
+ this.unusableResponsesInBreak = 0;
2651
+ adPlayer.stop().catch(function() {});
2652
+ if (!alreadyEnded) this.logBreakFunnel(reason);
2653
+ this.setSlotState("IDLE", "break_complete");
2719
2654
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
2720
2655
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
2721
2656
  if (this.host.video.muted !== restoredMuted) {
@@ -3009,25 +2944,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
3009
2944
  {
3010
2945
  key: "handleAdFailure",
3011
2946
  value: function handleAdFailure() {
3012
- this.timing.consecutiveFailures++;
3013
- this.timing.recordGamNoFill();
3014
- var remaining = this.timing.getRemainingAdMs();
3015
- if (this.debug) {
3016
- 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 ? {
3017
- queuedUrls: _to_consumable_array(this.adRequestQueue)
3018
- } : {});
3019
- }
3020
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
3021
- if (this.debug) console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
3022
- this.handleAdPodComplete();
2947
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "ad_failure";
2948
+ if (!this.inAdBreak) return;
2949
+ if (this.slotState === "REQUESTING" || this.slotState === "ENDING") {
2950
+ this.logOrchestratorFunnel("failure_deferred_to_request", {
2951
+ reason: reason,
2952
+ state: this.slotState
2953
+ });
3023
2954
  return;
3024
2955
  }
3025
- if (this.timing.hasTimeToStartAnotherAd()) {
3026
- this.tryNextAvailableAdWithRateLimit();
3027
- } else {
3028
- if (this.debug) console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:", this.timing.failedVastUrls.size);
3029
- this.handleAdPodComplete();
2956
+ this.timing.consecutiveFailures++;
2957
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
2958
+ if (diag && !diag.failureReason) diag.failureReason = reason;
2959
+ if (this.debug) {
2960
+ console.log("[AdBreak] Ad failure (".concat(reason, "): remaining=").concat(this.timing.getRemainingAdMs(), "ms, consecutiveFailures=").concat(this.timing.consecutiveFailures));
3030
2961
  }
2962
+ this.setSlotState("NEEDS_NEXT_AD", reason);
2963
+ this.requestNextAd(reason);
3031
2964
  }
3032
2965
  }
3033
2966
  ]);