function N() {
  let a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  return { id: a.id || null, adId: a.adId || null, sequence: a.sequence || null, apiFramework: a.apiFramework || null, universalAdIds: [], creativeExtensions: [] };
}
const G = ["ADCATEGORIES", "ADCOUNT", "ADPLAYHEAD", "ADSERVINGID", "ADTYPE", "APIFRAMEWORKS", "APPBUNDLE", "ASSETURI", "BLOCKEDADCATEGORIES", "BREAKMAXADLENGTH", "BREAKMAXADS", "BREAKMAXDURATION", "BREAKMINADLENGTH", "BREAKMINDURATION", "BREAKPOSITION", "CLICKPOS", "CLICKTYPE", "CLIENTUA", "CONTENTID", "CONTENTPLAYHEAD", "CONTENTURI", "DEVICEIP", "DEVICEUA", "DOMAIN", "EXTENSIONS", "GDPRCONSENT", "IFA", "IFATYPE", "INVENTORYSTATE", "LATLONG", "LIMITADTRACKING", "MEDIAMIME", "MEDIAPLAYHEAD", "OMIDPARTNER", "PAGEURL", "PLACEMENTTYPE", "PLAYERCAPABILITIES", "PLAYERSIZE", "PLAYERSTATE", "PODSEQUENCE", "REGULATIONS", "SERVERSIDE", "SERVERUA", "TRANSACTIONID", "UNIVERSALADID", "VASTVERSIONS", "VERIFICATIONVENDORS"];
function w(a) {
  let e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, t = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  const r = [], s = M(a);
  !e.ERRORCODE || t.isCustomCode || /^[0-9]{3}$/.test(e.ERRORCODE) || (e.ERRORCODE = 900), e.CACHEBUSTING = q(Math.round(1e8 * Math.random())), e.TIMESTAMP = (/* @__PURE__ */ new Date()).toISOString(), e.RANDOM = e.random = e.CACHEBUSTING;
  for (const i in e) e[i] = j(e[i]);
  for (const i in s) {
    const o = s[i];
    typeof o == "string" && r.push(B(o, e));
  }
  return r;
}
function B(a, e) {
  const t = (a = L(a, e)).match(/[^[\]]+(?=])/g);
  if (!t) return a;
  let r = t.filter((s) => G.indexOf(s) > -1);
  return r.length === 0 ? a : (r = r.reduce((s, i) => (s[i] = -1, s), {}), L(a, r));
}
function L(a, e) {
  let t = a;
  for (const r in e) {
    const s = e[r];
    t = t.replace(new RegExp("(?:\\[|%%)(".concat(r, ")(?:\\]|%%)"), "g"), s);
  }
  return t;
}
function M(a) {
  return Array.isArray(a) ? a.map((e) => e && e.hasOwnProperty("url") ? e.url : e) : a;
}
function C(a) {
  return /^(https?:\/\/|\/\/)/.test(a);
}
function U(a, e) {
  for (let t = 0; t < e.length; t++) if (W(e[t], a)) return !0;
  return !1;
}
function W(a, e) {
  if (a && e) {
    const t = Object.getOwnPropertyNames(a), r = Object.getOwnPropertyNames(e);
    return t.length === r.length && a.id === e.id && a.url === e.url;
  }
  return !1;
}
function j(a) {
  return encodeURIComponent(a).replace(/[!'()*]/g, (e) => "%".concat(e.charCodeAt(0).toString(16)));
}
function q(a) {
  let e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 8;
  return a.toString().padStart(e, "0");
}
const T = { track: function(a, e, t) {
  w(a, e, t).forEach((r) => {
    typeof window < "u" && window !== null && (new Image().src = r);
  });
}, resolveURLTemplates: w, extractURLsFromTemplates: M, filterUrlTemplates: function(a) {
  return a.reduce((e, t) => {
    const r = t.url || t;
    return C(r) ? e.validUrls.push(r) : e.invalidUrls.push(r), e;
  }, { validUrls: [], invalidUrls: [] });
}, containsTemplateObject: U, isTemplateObjectEqual: W, encodeURIComponentRFC3986: j, replaceUrlMacros: B, isNumeric: function(a) {
  return !isNaN(parseFloat(a)) && isFinite(a);
}, flatten: function a(e) {
  return e.reduce((t, r) => t.concat(Array.isArray(r) ? a(r) : r), []);
}, joinArrayOfUniqueTemplateObjs: function() {
  let a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], e = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
  const t = Array.isArray(a) ? a : [], r = Array.isArray(e) ? e : [];
  return t.concat(r).reduce((s, i) => (U(i, s) || s.push(i), s), []);
}, isValidTimeValue: function(a) {
  return Number.isFinite(a) && a >= -2;
}, addLeadingZeros: q, isValidUrl: C, isBrowserEnvironment: function() {
  return typeof window < "u";
}, formatMacrosValues: function(a) {
  return typeof a != "object" ? a : JSON.stringify(a);
} };
function I(a) {
  return ["true", "TRUE", "True", "1"].includes(a);
}
function Y(a) {
  if (a == null) return -1;
  if (T.isNumeric(a)) return parseInt(a);
  const e = a.split(":");
  if (e.length !== 3) return -1;
  const t = e[2].split(".");
  let r = parseInt(t[0]);
  t.length === 2 && (r += parseFloat("0.".concat(t[1])));
  const s = parseInt(60 * e[1]), i = parseInt(60 * e[0] * 60);
  return isNaN(i) || isNaN(s) || isNaN(r) || s > 3600 || r > 60 ? -1 : i + s + r;
}
const l = { childByName: function(a, e) {
  return Array.from(a.childNodes).find((t) => t.nodeName === e);
}, childrenByName: function(a, e) {
  return Array.from(a.childNodes).filter((t) => t.nodeName === e);
}, resolveVastAdTagURI: function(a, e) {
  if (!e) return a;
  if (a.startsWith("//")) {
    const { protocol: t } = location;
    return "".concat(t).concat(a);
  }
  if (!a.includes("://")) {
    const t = e.slice(0, e.lastIndexOf("/"));
    return "".concat(t, "/").concat(a);
  }
  return a;
}, parseBoolean: I, parseNodeText: function(a) {
  return a && (a.textContent || a.text || "").trim();
}, copyNodeAttribute: function(a, e, t) {
  const r = e.getAttribute(a);
  r && t.setAttribute(a, r);
}, parseAttributes: function(a) {
  return Array.from(a.attributes).reduce((e, t) => (e[t.nodeName] = t.nodeValue, e), {});
}, parseDuration: Y, getStandAloneAds: function() {
  return (arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : []).filter((a) => !parseInt(a.sequence, 10));
}, getSortedAdPods: function() {
  return (arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : []).filter((a) => parseInt(a.sequence, 10)).sort((a, e) => a.sequence - e.sequence);
}, assignAttributes: function(a, e) {
  a && Array.from(a).forEach((t) => {
    let { nodeName: r, nodeValue: s } = t;
    if (r && s && e.hasOwnProperty(r)) {
      let i = s;
      typeof e[r] == "boolean" && (i = I(i)), e[r] = i;
    }
  });
}, mergeWrapperAdData: function(a, e) {
  var t;
  a.errorURLTemplates = e.errorURLTemplates.concat(a.errorURLTemplates), a.impressionURLTemplates = e.impressionURLTemplates.concat(a.impressionURLTemplates), a.extensions = e.extensions.concat(a.extensions), e.viewableImpression.length > 0 && (a.viewableImpression = [...a.viewableImpression, ...e.viewableImpression]), a.followAdditionalWrappers = e.followAdditionalWrappers, a.allowMultipleAds = e.allowMultipleAds, a.fallbackOnNoAd = e.fallbackOnNoAd;
  const r = (e.creatives || []).filter((n) => n && n.type === "companion"), s = r.reduce((n, c) => ((c.variations || []).forEach((u) => {
    (u.companionClickTrackingURLTemplates || []).forEach((d) => {
      T.containsTemplateObject(d, n) || n.push(d);
    });
  }), n), []);
  a.creatives = r.concat(a.creatives);
  const i = e.videoClickTrackingURLTemplates && e.videoClickTrackingURLTemplates.length, o = e.videoCustomClickURLTemplates && e.videoCustomClickURLTemplates.length;
  if (a.creatives.forEach((n) => {
    if (e.trackingEvents && e.trackingEvents[n.type]) for (const c in e.trackingEvents[n.type]) {
      const u = e.trackingEvents[n.type][c];
      Array.isArray(n.trackingEvents[c]) || (n.trackingEvents[c] = []), n.trackingEvents[c] = n.trackingEvents[c].concat(u);
    }
    n.type === "linear" && (i && (n.videoClickTrackingURLTemplates = n.videoClickTrackingURLTemplates.concat(e.videoClickTrackingURLTemplates)), o && (n.videoCustomClickURLTemplates = n.videoCustomClickURLTemplates.concat(e.videoCustomClickURLTemplates)), !e.videoClickThroughURLTemplate || n.videoClickThroughURLTemplate !== null && n.videoClickThroughURLTemplate !== void 0 || (n.videoClickThroughURLTemplate = e.videoClickThroughURLTemplate)), n.type === "companion" && s.length && (n.variations || []).forEach((c) => {
      c.companionClickTrackingURLTemplates = T.joinArrayOfUniqueTemplateObjs(c.companionClickTrackingURLTemplates, s);
    });
  }), e.adVerifications && (a.adVerifications = a.adVerifications.concat(e.adVerifications)), e.blockedAdCategories && (a.blockedAdCategories = a.blockedAdCategories.concat(e.blockedAdCategories)), (t = e.creatives) !== null && t !== void 0 && t.length) {
    const n = e.creatives.filter((c) => {
      var u;
      return ((u = c.icons) === null || u === void 0 ? void 0 : u.length) && !c.mediaFiles.length;
    });
    n.length && (a.creatives = a.creatives.concat(n));
  }
} };
function Q(a, e) {
  const t = function() {
    let r = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    const { id: s, adId: i, sequence: o, apiFramework: n } = N(r);
    return { id: s, adId: i, sequence: o, apiFramework: n, type: "companion", required: null, variations: [] };
  }(e);
  return t.required = a.getAttribute("required") || null, t.variations = l.childrenByName(a, "Companion").map((r) => {
    const s = function() {
      let n = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      return { id: n.id || null, adType: "companionAd", width: n.width || 0, height: n.height || 0, assetWidth: n.assetWidth || null, assetHeight: n.assetHeight || null, expandedWidth: n.expandedWidth || null, expandedHeight: n.expandedHeight || null, apiFramework: n.apiFramework || null, adSlotId: n.adSlotId || null, pxratio: n.pxratio || "1", renderingMode: n.renderingMode || "default", staticResources: [], htmlResources: [], iframeResources: [], adParameters: null, altText: null, companionClickThroughURLTemplate: null, companionClickTrackingURLTemplates: [], trackingEvents: {} };
    }(l.parseAttributes(r));
    s.htmlResources = l.childrenByName(r, "HTMLResource").reduce((n, c) => {
      const u = l.parseNodeText(c);
      return u ? n.concat(u) : n;
    }, []), s.iframeResources = l.childrenByName(r, "IFrameResource").reduce((n, c) => {
      const u = l.parseNodeText(c);
      return u ? n.concat(u) : n;
    }, []), s.staticResources = l.childrenByName(r, "StaticResource").reduce((n, c) => {
      const u = l.parseNodeText(c);
      return u ? n.concat({ url: u, creativeType: c.getAttribute("creativeType") || null }) : n;
    }, []), s.altText = l.parseNodeText(l.childByName(r, "AltText")) || null;
    const i = l.childByName(r, "TrackingEvents");
    i && l.childrenByName(i, "Tracking").forEach((n) => {
      const c = n.getAttribute("event"), u = l.parseNodeText(n);
      c && u && (Array.isArray(s.trackingEvents[c]) || (s.trackingEvents[c] = []), s.trackingEvents[c].push(u));
    }), s.companionClickTrackingURLTemplates = l.childrenByName(r, "CompanionClickTracking").map((n) => ({ id: n.getAttribute("id") || null, url: l.parseNodeText(n) })), s.companionClickThroughURLTemplate = l.parseNodeText(l.childByName(r, "CompanionClickThrough")) || null;
    const o = l.childByName(r, "AdParameters");
    return o && (s.adParameters = { value: l.parseNodeText(o), xmlEncoded: o.getAttribute("xmlEncoded") || null }), s;
  }), t;
}
function X(a, e) {
  let t;
  const r = function() {
    let c = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    const { id: u, adId: d, sequence: g, apiFramework: m } = N(c);
    return { id: u, adId: d, sequence: g, apiFramework: m, type: "linear", duration: 0, skipDelay: null, mediaFiles: [], mezzanine: null, interactiveCreativeFile: null, closedCaptionFiles: [], videoClickThroughURLTemplate: null, videoClickTrackingURLTemplates: [], videoCustomClickURLTemplates: [], adParameters: null, icons: [], trackingEvents: {} };
  }(e);
  r.duration = l.parseDuration(l.parseNodeText(l.childByName(a, "Duration")));
  const s = a.getAttribute("skipoffset");
  if (s == null) r.skipDelay = null;
  else if (s.charAt(s.length - 1) === "%" && r.duration !== -1) {
    const c = parseInt(s, 10);
    r.skipDelay = r.duration * (c / 100);
  } else r.skipDelay = l.parseDuration(s);
  const i = l.childByName(a, "VideoClicks");
  if (i) {
    const c = l.childByName(i, "ClickThrough");
    r.videoClickThroughURLTemplate = c ? { id: c.getAttribute("id") || null, url: l.parseNodeText(c) } : null, l.childrenByName(i, "ClickTracking").forEach((u) => {
      r.videoClickTrackingURLTemplates.push({ id: u.getAttribute("id") || null, url: l.parseNodeText(u) });
    }), l.childrenByName(i, "CustomClick").forEach((u) => {
      r.videoCustomClickURLTemplates.push({ id: u.getAttribute("id") || null, url: l.parseNodeText(u) });
    });
  }
  const o = l.childByName(a, "AdParameters");
  o && (r.adParameters = { value: l.parseNodeText(o), xmlEncoded: o.getAttribute("xmlEncoded") || null }), l.childrenByName(a, "TrackingEvents").forEach((c) => {
    l.childrenByName(c, "Tracking").forEach((u) => {
      let d = u.getAttribute("event");
      const g = l.parseNodeText(u);
      if (d && g) {
        if (d === "progress") {
          if (t = u.getAttribute("offset"), !t) return;
          d = t.charAt(t.length - 1) === "%" ? "progress-".concat(t) : "progress-".concat(l.parseDuration(t));
        }
        Array.isArray(r.trackingEvents[d]) || (r.trackingEvents[d] = []), r.trackingEvents[d].push(g);
      }
    });
  }), l.childrenByName(a, "MediaFiles").forEach((c) => {
    l.childrenByName(c, "MediaFile").forEach((h) => {
      r.mediaFiles.push(function(p) {
        const v = { id: null, fileURL: null, fileSize: 0, deliveryType: "progressive", mimeType: null, mediaType: null, codec: null, bitrate: 0, minBitrate: 0, maxBitrate: 0, width: 0, height: 0, apiFramework: null, scalable: null, maintainAspectRatio: null };
        v.id = p.getAttribute("id"), v.fileURL = l.parseNodeText(p), v.deliveryType = p.getAttribute("delivery"), v.codec = p.getAttribute("codec"), v.mimeType = p.getAttribute("type"), v.mediaType = p.getAttribute("mediaType") || "2D", v.apiFramework = p.getAttribute("apiFramework"), v.fileSize = parseInt(p.getAttribute("fileSize") || 0), v.bitrate = parseInt(p.getAttribute("bitrate") || 0), v.minBitrate = parseInt(p.getAttribute("minBitrate") || 0), v.maxBitrate = parseInt(p.getAttribute("maxBitrate") || 0), v.width = parseInt(p.getAttribute("width") || 0), v.height = parseInt(p.getAttribute("height") || 0);
        const R = p.getAttribute("scalable");
        R && typeof R == "string" && (v.scalable = l.parseBoolean(R));
        const A = p.getAttribute("maintainAspectRatio");
        return A && typeof A == "string" && (v.maintainAspectRatio = l.parseBoolean(A)), v;
      }(h));
    });
    const u = l.childByName(c, "InteractiveCreativeFile");
    u && (r.interactiveCreativeFile = function(h) {
      const p = function() {
        let v = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
        return { type: v.type || null, apiFramework: v.apiFramework || null, variableDuration: l.parseBoolean(v.variableDuration), fileURL: null };
      }(l.parseAttributes(h));
      return p.fileURL = l.parseNodeText(h), p;
    }(u));
    const d = l.childByName(c, "ClosedCaptionFiles");
    d && l.childrenByName(d, "ClosedCaptionFile").forEach((h) => {
      const p = function() {
        let v = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
        return { type: v.type || null, language: v.language || null, fileURL: null };
      }(l.parseAttributes(h));
      p.fileURL = l.parseNodeText(h), r.closedCaptionFiles.push(p);
    });
    const g = l.childByName(c, "Mezzanine"), m = function(h, p) {
      const v = {};
      let R = !1;
      return p.forEach((A) => {
        h && h.getAttribute(A) ? v[A] = h.getAttribute(A) : R = !0;
      }), R ? null : v;
    }(g, ["delivery", "type", "width", "height"]);
    if (m) {
      const h = { id: null, fileURL: null, delivery: null, codec: null, type: null, width: 0, height: 0, fileSize: 0, mediaType: "2D" };
      h.id = g.getAttribute("id"), h.fileURL = l.parseNodeText(g), h.delivery = m.delivery, h.codec = g.getAttribute("codec"), h.type = m.type, h.width = parseInt(m.width, 10), h.height = parseInt(m.height, 10), h.fileSize = parseInt(g.getAttribute("fileSize"), 10), h.mediaType = g.getAttribute("mediaType") || "2D", r.mezzanine = h;
    }
  });
  const n = l.childByName(a, "Icons");
  return n && l.childrenByName(n, "Icon").forEach((c) => {
    r.icons.push(function(u) {
      const d = { program: null, height: 0, width: 0, xPosition: 0, yPosition: 0, apiFramework: null, offset: null, duration: 0, type: null, staticResource: null, htmlResource: null, iframeResource: null, pxratio: "1", iconClickThroughURLTemplate: null, iconClickTrackingURLTemplates: [], iconViewTrackingURLTemplate: null, iconClickFallbackImages: [], altText: null, hoverText: null };
      d.program = u.getAttribute("program"), d.height = parseInt(u.getAttribute("height") || 0), d.width = parseInt(u.getAttribute("width") || 0), d.xPosition = function(m) {
        return ["left", "right"].indexOf(m) !== -1 ? m : parseInt(m || 0);
      }(u.getAttribute("xPosition")), d.yPosition = function(m) {
        return ["top", "bottom"].indexOf(m) !== -1 ? m : parseInt(m || 0);
      }(u.getAttribute("yPosition")), d.apiFramework = u.getAttribute("apiFramework"), d.pxratio = u.getAttribute("pxratio") || "1", d.offset = l.parseDuration(u.getAttribute("offset")), d.duration = l.parseDuration(u.getAttribute("duration")), d.altText = u.getAttribute("altText"), d.hoverText = u.getAttribute("hoverText"), l.childrenByName(u, "HTMLResource").forEach((m) => {
        d.type = m.getAttribute("creativeType") || "text/html", d.htmlResource = l.parseNodeText(m);
      }), l.childrenByName(u, "IFrameResource").forEach((m) => {
        d.type = m.getAttribute("creativeType") || 0, d.iframeResource = l.parseNodeText(m);
      }), l.childrenByName(u, "StaticResource").forEach((m) => {
        d.type = m.getAttribute("creativeType") || 0, d.staticResource = l.parseNodeText(m);
      });
      const g = l.childByName(u, "IconClicks");
      if (g) {
        d.iconClickThroughURLTemplate = l.parseNodeText(l.childByName(g, "IconClickThrough")), l.childrenByName(g, "IconClickTracking").forEach((h) => {
          d.iconClickTrackingURLTemplates.push({ id: h.getAttribute("id") || null, url: l.parseNodeText(h) });
        });
        const m = l.childByName(g, "IconClickFallbackImages");
        m && l.childrenByName(m, "IconClickFallbackImage").forEach((h) => {
          d.iconClickFallbackImages.push({ url: l.parseNodeText(h) || null, width: h.getAttribute("width") || null, height: h.getAttribute("height") || null });
        });
      }
      return d.iconViewTrackingURLTemplate = l.parseNodeText(l.childByName(u, "IconViewTracking")), d;
    }(c));
  }), r;
}
function Z(a, e) {
  const t = function() {
    let r = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    const { id: s, adId: i, sequence: o, apiFramework: n } = N(r);
    return { id: s, adId: i, sequence: o, apiFramework: n, type: "nonlinear", variations: [], trackingEvents: {} };
  }(e);
  return l.childrenByName(a, "TrackingEvents").forEach((r) => {
    let s, i;
    l.childrenByName(r, "Tracking").forEach((o) => {
      s = o.getAttribute("event"), i = l.parseNodeText(o), s && i && (Array.isArray(t.trackingEvents[s]) || (t.trackingEvents[s] = []), t.trackingEvents[s].push(i));
    });
  }), l.childrenByName(a, "NonLinear").forEach((r) => {
    const s = { id: null, width: 0, height: 0, expandedWidth: 0, expandedHeight: 0, scalable: !0, maintainAspectRatio: !0, minSuggestedDuration: 0, apiFramework: "static", adType: "nonLinearAd", type: null, staticResource: null, htmlResource: null, iframeResource: null, nonlinearClickThroughURLTemplate: null, nonlinearClickTrackingURLTemplates: [], adParameters: null };
    s.id = r.getAttribute("id") || null, s.width = r.getAttribute("width"), s.height = r.getAttribute("height"), s.expandedWidth = r.getAttribute("expandedWidth"), s.expandedHeight = r.getAttribute("expandedHeight"), s.scalable = l.parseBoolean(r.getAttribute("scalable")), s.maintainAspectRatio = l.parseBoolean(r.getAttribute("maintainAspectRatio")), s.minSuggestedDuration = l.parseDuration(r.getAttribute("minSuggestedDuration")), s.apiFramework = r.getAttribute("apiFramework"), l.childrenByName(r, "HTMLResource").forEach((o) => {
      s.type = o.getAttribute("creativeType") || "text/html", s.htmlResource = l.parseNodeText(o);
    }), l.childrenByName(r, "IFrameResource").forEach((o) => {
      s.type = o.getAttribute("creativeType") || 0, s.iframeResource = l.parseNodeText(o);
    }), l.childrenByName(r, "StaticResource").forEach((o) => {
      s.type = o.getAttribute("creativeType") || 0, s.staticResource = l.parseNodeText(o);
    });
    const i = l.childByName(r, "AdParameters");
    i && (s.adParameters = { value: l.parseNodeText(i), xmlEncoded: i.getAttribute("xmlEncoded") || null }), s.nonlinearClickThroughURLTemplate = l.parseNodeText(l.childByName(r, "NonLinearClickThrough")), l.childrenByName(r, "NonLinearClickTracking").forEach((o) => {
      s.nonlinearClickTrackingURLTemplates.push({ id: o.getAttribute("id") || null, url: l.parseNodeText(o) });
    }), t.variations.push(s);
  }), t;
}
function x(a) {
  const e = [];
  return a.forEach((t) => {
    const r = K(t);
    r && e.push(r);
  }), e;
}
function K(a) {
  if (a.nodeName === "#comment") return null;
  const e = { name: null, value: null, attributes: {}, children: [] }, t = a.attributes, r = a.childNodes;
  if (e.name = a.nodeName, a.attributes) {
    for (const i in t) if (t.hasOwnProperty(i)) {
      const o = t[i];
      o.nodeName && o.nodeValue && (e.attributes[o.nodeName] = o.nodeValue);
    }
  }
  for (const i in r) if (r.hasOwnProperty(i)) {
    const o = K(r[i]);
    o && e.children.push(o);
  }
  if (e.children.length === 0 || e.children.length === 1 && ["#cdata-section", "#text"].indexOf(e.children[0].name) >= 0) {
    const i = l.parseNodeText(a);
    i !== "" && (e.value = i), e.children = [];
  }
  return (s = e).value === null && Object.keys(s.attributes).length === 0 && s.children.length === 0 ? null : e;
  var s;
}
function J(a) {
  return a.getAttribute("AdID") || a.getAttribute("adID") || a.getAttribute("adId") || null;
}
const y = { Wrapper: { subElements: ["VASTAdTagURI", "Impression"] }, BlockedAdCategories: { attributes: ["authority"] }, InLine: { subElements: ["AdSystem", "AdTitle", "Impression", "AdServingId", "Creatives"] }, Category: { attributes: ["authority"] }, Pricing: { attributes: ["model", "currency"] }, Verification: { oneOfinLineResources: ["JavaScriptResource", "ExecutableResource"], attributes: ["vendor"] }, UniversalAdId: { attributes: ["idRegistry"] }, JavaScriptResource: { attributes: ["apiFramework", "browserOptional"] }, ExecutableResource: { attributes: ["apiFramework", "type"] }, Tracking: { attributes: ["event"] }, Creatives: { subElements: ["Creative"] }, Creative: { subElements: ["UniversalAdId"] }, Linear: { subElements: ["MediaFiles", "Duration"] }, MediaFiles: { subElements: ["MediaFile"] }, MediaFile: { attributes: ["delivery", "type", "width", "height"] }, Mezzanine: { attributes: ["delivery", "type", "width", "height"] }, NonLinear: { oneOfinLineResources: ["StaticResource", "IFrameResource", "HTMLResource"], attributes: ["width", "height"] }, Companion: { oneOfinLineResources: ["StaticResource", "IFrameResource", "HTMLResource"], attributes: ["width", "height"] }, StaticResource: { attributes: ["creativeType"] }, Icons: { subElements: ["Icon"] }, Icon: { oneOfinLineResources: ["StaticResource", "IFrameResource", "HTMLResource"] } };
function S(a, e) {
  if (!y[a.nodeName] || !y[a.nodeName].attributes) return;
  const t = y[a.nodeName].attributes.filter((r) => !a.getAttribute(r));
  t.length > 0 && k({ name: a.nodeName, parentName: a.parentNode.nodeName, attributes: t }, e);
}
function V(a, e, t) {
  const r = y[a.nodeName], s = !t && a.nodeName !== "Wrapper";
  if (!(!r || s)) {
    if (r.subElements) {
      const i = r.subElements.filter((o) => !l.childByName(a, o));
      i.length > 0 && k({ name: a.nodeName, parentName: a.parentNode.nodeName, subElements: i }, e);
    }
    !t || !r.oneOfinLineResources || r.oneOfinLineResources.some((i) => l.childByName(a, i)) || k({ name: a.nodeName, parentName: a.parentNode.nodeName, oneOfResources: r.oneOfinLineResources }, e);
  }
}
function D(a) {
  return a.children && a.children.length !== 0;
}
function k(a, e) {
  let { name: t, parentName: r, attributes: s, subElements: i, oneOfResources: o } = a, n = "Element '".concat(t, "'");
  n += s ? " missing required attribute(s) '".concat(s.join(", "), "' ") : i ? " missing required sub element(s) '".concat(i.join(", "), "' ") : o ? " must provide one of the following '".concat(o.join(", "), "' ") : " is empty", e("VAST-warning", { message: n, parentElement: r, specVersion: 4.1 });
}
const $ = { verifyRequiredValues: function a(e, t, r) {
  if (e && e.nodeName) if (e.nodeName === "InLine" && (r = !0), S(e, t), D(e)) {
    V(e, t, r);
    for (let s = 0; s < e.children.length; s++) a(e.children[s], t, r);
  } else l.parseNodeText(e).length === 0 && k({ name: e.nodeName, parentName: e.parentNode.nodeName }, t);
}, hasSubElements: D, emitMissingValueWarning: k, verifyRequiredAttributes: S, verifyRequiredSubElements: V };
function ee(a, e) {
  let { allowMultipleAds: t, followAdditionalWrappers: r } = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  const s = Array.from(a.childNodes).filter((i) => {
    const o = i.nodeName.toLowerCase();
    return o === "inline" || r !== !1 && o === "wrapper";
  });
  for (const i of s) {
    if (l.copyNodeAttribute("id", a, i), l.copyNodeAttribute("sequence", a, i), l.copyNodeAttribute("adType", a, i), i.nodeName === "Wrapper") return { ad: re(i, e), type: "WRAPPER" };
    if (i.nodeName === "InLine") return { ad: te(i, e, { allowMultipleAds: t }), type: "INLINE" };
    const o = i.nodeName.toLowerCase();
    e("VAST-warning", { message: "<".concat(i.nodeName, o === "inline" ? "> must be written <InLine>" : "> must be written <Wrapper>"), wrongNode: i });
  }
}
function te(a, e) {
  let { allowMultipleAds: t } = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  return t === !1 && a.getAttribute("sequence") ? null : H(a, e);
}
function H(a, e) {
  let t = [];
  e && $.verifyRequiredValues(a, e);
  const r = Array.from(a.childNodes), s = function() {
    let i = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    return { id: i.id || null, sequence: i.sequence || null, adType: i.adType || null, adServingId: null, categories: [], expires: null, viewableImpression: [], system: null, title: null, description: null, advertiser: null, pricing: null, survey: null, errorURLTemplates: [], impressionURLTemplates: [], creatives: [], extensions: [], adVerifications: [], blockedAdCategories: [], followAdditionalWrappers: !0, allowMultipleAds: !1, fallbackOnNoAd: null };
  }(l.parseAttributes(a));
  return r.forEach((i) => {
    switch (i.nodeName) {
      case "Error":
        s.errorURLTemplates.push(l.parseNodeText(i));
        break;
      case "Impression":
        s.impressionURLTemplates.push({ id: i.getAttribute("id") || null, url: l.parseNodeText(i) });
        break;
      case "Creatives":
        s.creatives = function(o) {
          const n = [];
          return o.forEach((c) => {
            const u = { id: c.getAttribute("id") || null, adId: J(c), sequence: c.getAttribute("sequence") || null, apiFramework: c.getAttribute("apiFramework") || null }, d = [];
            let g;
            l.childrenByName(c, "UniversalAdId").forEach((h) => {
              const p = { idRegistry: h.getAttribute("idRegistry") || "unknown", value: l.parseNodeText(h) };
              d.push(p);
            });
            const m = l.childByName(c, "CreativeExtensions");
            m && (g = x(l.childrenByName(m, "CreativeExtension")));
            for (const h in c.childNodes) {
              const p = c.childNodes[h];
              let v;
              switch (p.nodeName) {
                case "Linear":
                  v = X(p, u);
                  break;
                case "NonLinearAds":
                  v = Z(p, u);
                  break;
                case "CompanionAds":
                  v = Q(p, u);
              }
              v && (d && (v.universalAdIds = d), g && (v.creativeExtensions = g), n.push(v));
            }
          }), n;
        }(l.childrenByName(i, "Creative"));
        break;
      case "Extensions": {
        const o = l.childrenByName(i, "Extension");
        s.extensions = x(o), s.adVerifications.length || (t = function(n) {
          let c = null, u = [];
          return n.some((d) => c = l.childByName(d, "AdVerifications")), c && (u = O(l.childrenByName(c, "Verification"))), u;
        }(o));
        break;
      }
      case "AdVerifications":
        s.adVerifications = O(l.childrenByName(i, "Verification"));
        break;
      case "AdSystem":
        s.system = { value: l.parseNodeText(i), version: i.getAttribute("version") || null };
        break;
      case "AdTitle":
        s.title = l.parseNodeText(i);
        break;
      case "AdServingId":
        s.adServingId = l.parseNodeText(i);
        break;
      case "Category":
        s.categories.push({ authority: i.getAttribute("authority") || null, value: l.parseNodeText(i) });
        break;
      case "Expires":
        s.expires = parseInt(l.parseNodeText(i), 10);
        break;
      case "ViewableImpression":
        s.viewableImpression.push(function(o) {
          const n = (c, u) => {
            const d = l.parseNodeText(u);
            return d && c.push(d), c;
          };
          return { id: o.getAttribute("id") || null, viewable: l.childrenByName(o, "Viewable").reduce(n, []), notViewable: l.childrenByName(o, "NotViewable").reduce(n, []), viewUndetermined: l.childrenByName(o, "ViewUndetermined").reduce(n, []) };
        }(i));
        break;
      case "Description":
        s.description = l.parseNodeText(i);
        break;
      case "Advertiser":
        s.advertiser = { id: i.getAttribute("id") || null, value: l.parseNodeText(i) };
        break;
      case "Pricing":
        s.pricing = { value: l.parseNodeText(i), model: i.getAttribute("model") || null, currency: i.getAttribute("currency") || null };
        break;
      case "Survey":
        s.survey = { value: l.parseNodeText(i), type: i.getAttribute("type") || null };
        break;
      case "BlockedAdCategories":
        s.blockedAdCategories.push({ authority: i.getAttribute("authority") || null, value: l.parseNodeText(i) });
    }
  }), t.length && (s.adVerifications = s.adVerifications.concat(t)), s;
}
function re(a, e) {
  const t = H(a, e), r = a.getAttribute("followAdditionalWrappers"), s = a.getAttribute("allowMultipleAds"), i = a.getAttribute("fallbackOnNoAd");
  t.followAdditionalWrappers = !r || l.parseBoolean(r), t.allowMultipleAds = !!s && l.parseBoolean(s), t.fallbackOnNoAd = i ? l.parseBoolean(i) : null;
  let o = l.childByName(a, "VASTAdTagURI");
  if (o ? t.nextWrapperURL = l.parseNodeText(o) : (o = l.childByName(a, "VASTAdTagURL"), o && (t.nextWrapperURL = l.parseNodeText(l.childByName(o, "URL")))), t.creatives.forEach((n) => {
    if (["linear", "nonlinear"].includes(n.type)) {
      if (n.trackingEvents) {
        t.trackingEvents || (t.trackingEvents = {}), t.trackingEvents[n.type] || (t.trackingEvents[n.type] = {});
        for (const c in n.trackingEvents) {
          const u = n.trackingEvents[c];
          Array.isArray(t.trackingEvents[n.type][c]) || (t.trackingEvents[n.type][c] = []), u.forEach((d) => {
            t.trackingEvents[n.type][c].push(d);
          });
        }
      }
      n.videoClickTrackingURLTemplates && (Array.isArray(t.videoClickTrackingURLTemplates) || (t.videoClickTrackingURLTemplates = []), n.videoClickTrackingURLTemplates.forEach((c) => {
        t.videoClickTrackingURLTemplates.push(c);
      })), n.videoClickThroughURLTemplate && (t.videoClickThroughURLTemplate = n.videoClickThroughURLTemplate), n.videoCustomClickURLTemplates && (Array.isArray(t.videoCustomClickURLTemplates) || (t.videoCustomClickURLTemplates = []), n.videoCustomClickURLTemplates.forEach((c) => {
        t.videoCustomClickURLTemplates.push(c);
      }));
    }
  }), t.nextWrapperURL) return t;
}
function O(a) {
  const e = [];
  return a.forEach((t) => {
    const r = { resource: null, vendor: null, browserOptional: !1, apiFramework: null, type: null, parameters: null, trackingEvents: {} }, s = Array.from(t.childNodes);
    l.assignAttributes(t.attributes, r), s.forEach((o) => {
      let { nodeName: n, textContent: c, attributes: u } = o;
      switch (n) {
        case "JavaScriptResource":
        case "ExecutableResource":
          r.resource = c.trim(), l.assignAttributes(u, r);
          break;
        case "VerificationParameters":
          r.parameters = c.trim();
      }
    });
    const i = l.childByName(t, "TrackingEvents");
    i && l.childrenByName(i, "Tracking").forEach((o) => {
      const n = o.getAttribute("event"), c = l.parseNodeText(o);
      n && c && (Array.isArray(r.trackingEvents[n]) || (r.trackingEvents[n] = []), r.trackingEvents[n].push(c));
    }), e.push(r);
  }), e;
}
class _ {
  constructor() {
    this._handlers = [];
  }
  on(e, t) {
    if (typeof t != "function") throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof t));
    if (!e) throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));
    return this._handlers.push({ event: e, handler: t }), this;
  }
  once(e, t) {
    return this.on(e, function(r, s, i) {
      const o = { fired: !1, wrapFn: void 0 };
      function n() {
        o.fired || (r.off(s, o.wrapFn), o.fired = !0, i.bind(r)(...arguments));
      }
      return o.wrapFn = n, n;
    }(this, e, t));
  }
  off(e, t) {
    return this._handlers = this._handlers.filter((r) => r.event !== e || r.handler !== t), this;
  }
  emit(e) {
    for (var t = arguments.length, r = new Array(t > 1 ? t - 1 : 0), s = 1; s < t; s++) r[s - 1] = arguments[s];
    let i = !1;
    return this._handlers.forEach((o) => {
      o.event === "*" && (i = !0, o.handler(e, ...r)), o.event === e && (i = !0, o.handler(...r));
    }), i;
  }
  removeAllListeners(e) {
    return e ? (this._handlers = this._handlers.filter((t) => t.event !== e), this) : (this._handlers = [], this);
  }
  listenerCount(e) {
    return this._handlers.filter((t) => t.event === e).length;
  }
  listeners(e) {
    return this._handlers.reduce((t, r) => (r.event === e && t.push(r.handler), t), []);
  }
  eventNames() {
    return this._handlers.map((e) => e.event);
  }
}
let F = 0, E = 0;
const z = (a, e) => {
  !a || !e || a <= 0 || e <= 0 || (E = (E * F + 8 * a / e) / ++F);
}, ae = { ERRORCODE: 900, extensions: [] }, P = "VAST response version not supported";
class se extends _ {
  constructor() {
    let { fetcher: e } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    super(), this.maxWrapperDepth = null, this.rootErrorURLTemplates = [], this.errorURLTemplates = [], this.remainingAds = [], this.parsingOptions = {}, this.fetcher = e || null, this.keepFailedAdPod = !1;
  }
  trackVastError(e, t) {
    for (var r = arguments.length, s = new Array(r > 2 ? r - 2 : 0), i = 2; i < r; i++) s[i - 2] = arguments[i];
    this.emit("VAST-error", Object.assign({}, ae, t, ...s)), T.track(e, t);
  }
  getErrorURLTemplates() {
    return this.rootErrorURLTemplates.concat(this.errorURLTemplates);
  }
  getEstimatedBitrate() {
    return E;
  }
  initParsingStatus() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    this.maxWrapperDepth = e.wrapperLimit || 10, this.parsingOptions = { allowMultipleAds: e.allowMultipleAds }, this.keepFailedAdPod = e.keepFailedAdPod || !1, this.rootURL = "", this.resetParsingStatus(), z(e.byteLength, e.requestDuration);
  }
  resetParsingStatus() {
    this.errorURLTemplates = [], this.rootErrorURLTemplates = [], this.vastVersion = null;
  }
  getRemainingAds(e) {
    if (this.remainingAds.length === 0) return Promise.reject(new Error("No more ads are available for the given VAST"));
    const t = e ? this.remainingAds : [this.remainingAds.shift()];
    return this.errorURLTemplates = [], this.resolveAds(t, { wrapperDepth: 0, url: this.rootURL }).then((r) => this.buildVASTResponse(r));
  }
  parseVAST(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    return this.initParsingStatus(t), t.isRootVAST = !0, this.parse(e, t).then((r) => this.buildVASTResponse(r));
  }
  buildVASTResponse(e) {
    const t = function(r) {
      let { ads: s, errorURLTemplates: i, version: o } = r;
      return { ads: s || [], errorURLTemplates: i || [], version: o || null };
    }({ ads: e, errorURLTemplates: this.getErrorURLTemplates(), version: this.vastVersion });
    return this.completeWrapperResolving(t), t;
  }
  parseVastXml(e, t) {
    let { isRootVAST: r = !1, url: s = null, wrapperDepth: i = 0, allowMultipleAds: o, followAdditionalWrappers: n } = t;
    if (!e || !e.documentElement || e.documentElement.nodeName !== "VAST") {
      var c;
      this.emit("VAST-ad-parsed", { type: "ERROR", url: s, wrapperDepth: i });
      const m = (e == null || (c = e.documentElement) === null || c === void 0 ? void 0 : c.nodeName) === "VideoAdServingTemplate";
      throw new Error(m ? P : "Invalid VAST XMLDocument");
    }
    const u = [], d = e.documentElement.childNodes, g = e.documentElement.getAttribute("version");
    r && g && (this.vastVersion = g);
    for (const m in d) {
      const h = d[m];
      if (h.nodeName === "Error") {
        const p = l.parseNodeText(h);
        r ? this.rootErrorURLTemplates.push(p) : this.errorURLTemplates.push(p);
      } else if (h.nodeName === "Ad") {
        if (this.vastVersion && parseFloat(this.vastVersion) < 3) o = !0;
        else if (o === !1 && u.length > 1) break;
        const p = ee(h, this.emit.bind(this), { allowMultipleAds: o, followAdditionalWrappers: n });
        p.ad ? (u.push(p.ad), this.emit("VAST-ad-parsed", { type: p.type, url: s, wrapperDepth: i, adIndex: u.length - 1, vastVersion: g })) : this.trackVastError(this.getErrorURLTemplates(), { ERRORCODE: 101 });
      }
    }
    return u;
  }
  parse(e) {
    let { url: t = null, resolveAll: r = !0, wrapperSequence: s = null, previousUrl: i = null, wrapperDepth: o = 0, isRootVAST: n = !1, followAdditionalWrappers: c, allowMultipleAds: u } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, d = [];
    this.vastVersion && parseFloat(this.vastVersion) < 3 && n && (u = !0);
    try {
      d = this.parseVastXml(e, { isRootVAST: n, url: t, wrapperDepth: o, allowMultipleAds: u, followAdditionalWrappers: c });
    } catch (g) {
      return Promise.reject(g);
    }
    if (d.length === 1 && s != null && (d[0].sequence = s), r === !1) {
      const g = l.getSortedAdPods(d), m = l.getStandAloneAds(d);
      g.length ? d = g : m.length && (d = [m.shift()]), this.remainingAds = m;
    }
    return this.resolveAds(d, { wrapperDepth: o, previousUrl: i, url: t });
  }
  resolveAds() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], { wrapperDepth: t, previousUrl: r, url: s } = arguments.length > 1 ? arguments[1] : void 0;
    const i = [];
    return r = s, e.forEach((o) => {
      const n = this.resolveWrappers(o, t, r);
      i.push(n);
    }), Promise.all(i).then((o) => T.flatten(o));
  }
  resolveWrappers(e, t, r) {
    const s = { ...e };
    return new Promise((i) => {
      var o;
      if (t++, !s.nextWrapperURL) return delete s.nextWrapperURL, i(s);
      if (!this.fetcher) return s.VASTAdTagURI = s.nextWrapperURL, delete s.nextWrapperURL, i(s);
      if (t >= this.maxWrapperDepth) return s.errorCode = 302, delete s.nextWrapperURL, i(s);
      s.nextWrapperURL = l.resolveVastAdTagURI(s.nextWrapperURL, r);
      const n = (o = this.parsingOptions.allowMultipleAds) !== null && o !== void 0 ? o : s.allowMultipleAds, c = s.sequence;
      this.fetcher.fetchVAST({ url: s.nextWrapperURL, emitter: this.emit.bind(this), maxWrapperDepth: this.maxWrapperDepth }).then((u) => this.parse(u, { url: s.nextWrapperURL, previousUrl: r, wrapperSequence: c, wrapperDepth: t, followAdditionalWrappers: s.followAdditionalWrappers, allowMultipleAds: n }).then((d) => {
        if (delete s.nextWrapperURL, d.length === 0) return s.creatives = [], i(s);
        d.forEach((g) => {
          g && l.mergeWrapperAdData(g, s);
        }), i(d);
      })).catch((u) => {
        s.errorCode = u.message === P ? 102 : 301, s.errorMessage = u.message, i(s);
      });
    });
  }
  completeWrapperResolving(e) {
    if (e.ads.length === 0) this.trackVastError(e.errorURLTemplates, { ERRORCODE: 303 });
    else for (let t = e.ads.length - 1; t >= 0; t--) {
      const r = e.ads[t], s = !r.creatives.some((i) => {
        var o, n;
        return ((o = i.mediaFiles) === null || o === void 0 ? void 0 : o.length) > 0 || ((n = i.variations) === null || n === void 0 ? void 0 : n.length) > 0;
      });
      !r.errorCode && !s || r.VASTAdTagURI || (this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates), { ERRORCODE: r.errorCode || 303 }, { ERRORMESSAGE: r.errorMessage || "" }, { extensions: r.extensions }, { system: r.system }), this.keepFailedAdPod && r.sequence ? r.hasFailed = !0 : e.ads.splice(t, 1));
    }
  }
}
let f = null;
const ie = { data: {}, length: 0, getItem(a) {
  return this.data[a];
}, setItem(a, e) {
  this.data[a] = e, this.length = Object.keys(this.data).length;
}, removeItem(a) {
  delete this.data[a], this.length = Object.keys(this.data).length;
}, clear() {
  this.data = {}, this.length = 0;
} };
class ne {
  constructor() {
    this.storage = this.initStorage();
  }
  initStorage() {
    if (f) return f;
    try {
      f = typeof window < "u" && window !== null ? window.localStorage || window.sessionStorage : null;
    } catch {
      f = null;
    }
    return f && !this.isStorageDisabled(f) || (f = ie, f.clear()), f;
  }
  isStorageDisabled(e) {
    const t = "__VASTStorage__";
    try {
      if (e.setItem(t, t), e.getItem(t) !== t) return e.removeItem(t), !0;
    } catch {
      return !0;
    }
    return e.removeItem(t), !1;
  }
  getItem(e) {
    return this.storage.getItem(e);
  }
  setItem(e, t) {
    return this.storage.setItem(e, t);
  }
  removeItem(e) {
    return this.storage.removeItem(e);
  }
  clear() {
    return this.storage.clear();
  }
}
const b = 12e4, oe = { get: async function(a, e) {
  try {
    const t = new AbortController(), r = setTimeout(() => {
      throw t.abort(), new Error("URLHandler: Request timed out after ".concat(e.timeout || b, " ms (408)"));
    }, e.timeout || b), s = await fetch(a, { ...e, signal: t.signal, credentials: e.withCredentials ? "include" : "omit" }).finally(() => {
      clearTimeout(r);
    }), i = function(o) {
      return T.isBrowserEnvironment() && window.location.protocol === "https:" && o.url.includes("http://") ? "URLHandler: Cannot go from HTTPS to HTTP." : o.status === 200 && o.ok ? null : "URLHandler: ".concat(o.statusText, " (").concat(o.status, ")");
    }(s);
    return i ? { error: new Error(i), statusCode: s.status } : async function(o) {
      const n = await o.text();
      let c;
      return c = T.isBrowserEnvironment() ? new DOMParser() : new (await import("./index-l-eyvmpL.js").then((u) => u.i)).DOMParser(), { xml: c.parseFromString(n, "text/xml"), details: { byteLength: n.length, statusCode: o.status, rawXml: n } };
    }(s);
  } catch (t) {
    return { error: t, statusCode: t.name === "AbortError" ? 408 : null };
  }
} };
class le {
  constructor() {
    this.URLTemplateFilters = [];
  }
  setOptions() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    this.urlHandler = e.urlHandler || e.urlhandler || oe, this.fetchingOptions = { ...e.fetchOptions, timeout: e.timeout || b, withCredentials: !!e.withCredentials };
  }
  addURLTemplateFilter(e) {
    typeof e == "function" && this.URLTemplateFilters.push(e);
  }
  removeLastURLTemplateFilter() {
    this.URLTemplateFilters.pop();
  }
  countURLTemplateFilters() {
    return this.URLTemplateFilters.length;
  }
  clearURLTemplateFilters() {
    this.URLTemplateFilters = [];
  }
  async fetchVAST(e) {
    var t;
    let { url: r, maxWrapperDepth: s, emitter: i, wrapperDepth: o = 0, previousUrl: n = null, wrapperAd: c = null } = e;
    const u = Date.now();
    this.URLTemplateFilters.forEach((m) => {
      r = m(r);
    }), i("VAST-resolving", { url: r, previousUrl: n, wrapperDepth: o, maxWrapperDepth: s, timeout: this.fetchingOptions.timeout, wrapperAd: c });
    const d = await this.urlHandler.get(r, this.fetchingOptions), g = Math.round(Date.now() - u);
    if (i("VAST-resolved", { url: r, previousUrl: n, wrapperDepth: o, error: (d == null ? void 0 : d.error) || null, duration: g, statusCode: (d == null ? void 0 : d.statusCode) || null, ...d == null ? void 0 : d.details }), z(d == null || (t = d.details) === null || t === void 0 ? void 0 : t.byteLength, g), d.error) throw new Error(d.error);
    return d.xml;
  }
}
class ce {
  constructor() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0, t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0, r = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : new ne();
    this.cappingFreeLunch = e, this.cappingMinimumTimeInterval = t, this.fetcher = new le(), this.vastParser = new se({ fetcher: this.fetcher }), this.storage = r, this.lastSuccessfulAd === void 0 && (this.lastSuccessfulAd = 0), this.totalCalls === void 0 && (this.totalCalls = 0), this.totalCallsTimeout === void 0 && (this.totalCallsTimeout = 0);
  }
  addURLTemplateFilter(e) {
    this.fetcher.addURLTemplateFilter(e);
  }
  removeLastURLTemplateFilter() {
    this.fetcher.removeLastURLTemplateFilter();
  }
  countURLTemplateFilters() {
    return this.fetcher.countURLTemplateFilters();
  }
  clearURLTemplateFilters() {
    this.fetcher.clearURLTemplateFilters();
  }
  getParser() {
    return this.vastParser;
  }
  get lastSuccessfulAd() {
    return this.storage.getItem("vast-client-last-successful-ad");
  }
  set lastSuccessfulAd(e) {
    this.storage.setItem("vast-client-last-successful-ad", e);
  }
  get totalCalls() {
    return this.storage.getItem("vast-client-total-calls");
  }
  set totalCalls(e) {
    this.storage.setItem("vast-client-total-calls", e);
  }
  get totalCallsTimeout() {
    return this.storage.getItem("vast-client-total-calls-timeout");
  }
  set totalCallsTimeout(e) {
    this.storage.setItem("vast-client-total-calls-timeout", e);
  }
  hasRemainingAds() {
    return this.vastParser.remainingAds.length > 0;
  }
  getNextAds(e) {
    return this.vastParser.getRemainingAds(e);
  }
  parseVAST(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    return this.fetcher.setOptions(t), this.vastParser.parseVAST(e, t);
  }
  get(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    const r = Date.now();
    return t.hasOwnProperty("resolveAll") || (t.resolveAll = !1), this.totalCallsTimeout < r ? (this.totalCalls = 1, this.totalCallsTimeout = r + 36e5) : this.totalCalls++, new Promise((s, i) => {
      if (this.cappingFreeLunch >= this.totalCalls) return i(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls, "/").concat(this.cappingFreeLunch)));
      const o = r - this.lastSuccessfulAd;
      if (o < 0) this.lastSuccessfulAd = 0;
      else if (o < this.cappingMinimumTimeInterval) return i(new Error("VAST call canceled – (".concat(this.cappingMinimumTimeInterval, ")ms minimum interval reached")));
      this.vastParser.initParsingStatus(t), this.fetcher.setOptions(t), this.vastParser.rootURL = e, this.fetcher.fetchVAST({ url: e, emitter: this.vastParser.emit.bind(this.vastParser), maxWrapperDepth: this.vastParser.maxWrapperDepth }).then((n) => (t.previousUrl = e, t.isRootVAST = !0, t.url = e, this.vastParser.parse(n, t).then((c) => {
        const u = this.vastParser.buildVASTResponse(c);
        s(u);
      }))).catch((n) => i(n));
    });
  }
}
class ue extends _ {
  constructor(e, t, r) {
    var s;
    let i = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null, o = arguments.length > 4 && arguments[4] !== void 0 && arguments[4];
    super(), this.ad = t, this.creative = r, this.variation = i, this.muted = o, this.impressed = !1, this.skippable = !1, this.trackingEvents = {}, this.trackedProgressEvents = [], this.lastPercentage = 0, this._alreadyTriggeredQuartiles = {}, this.emitAlwaysEvents = ["creativeView", "start", "firstQuartile", "midpoint", "thirdQuartile", "complete", "resume", "pause", "rewind", "skip", "closeLinear", "close"];
    for (const n in this.creative.trackingEvents) {
      const c = this.creative.trackingEvents[n];
      this.trackingEvents[n] = c.slice(0);
    }
    this.viewableImpressionTrackers = ((s = this.ad.viewableImpression) === null || s === void 0 ? void 0 : s.reduce((n, c) => (n.notViewable.push(...c.notViewable), n.viewUndetermined.push(...c.viewUndetermined), n.viewable.push(...c.viewable), n), { notViewable: [], viewUndetermined: [], viewable: [] })) || {}, Object.entries(this.viewableImpressionTrackers).forEach((n) => {
      let [c, u] = n;
      u.length && (this.trackingEvents[c] = u);
    }), function(n) {
      return n.type === "linear";
    }(this.creative) ? this._initLinearTracking() : this._initVariationTracking(), e && this.on("start", () => {
      e.lastSuccessfulAd = Date.now();
    });
  }
  _initLinearTracking() {
    this.linear = !0, this.skipDelay = this.creative.skipDelay, this.setDuration(this.creative.duration), this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate, this.clickTrackingURLTemplates = this.creative.videoClickTrackingURLTemplates;
  }
  _initVariationTracking() {
    if (this.linear = !1, this.skipDelay = -1, this.variation) {
      for (const e in this.variation.trackingEvents) {
        const t = this.variation.trackingEvents[e];
        this.trackingEvents[e] ? this.trackingEvents[e] = this.trackingEvents[e].concat(t.slice(0)) : this.trackingEvents[e] = t.slice(0);
      }
      this.variation.adType === "nonLinearAd" ? (this.clickThroughURLTemplate = this.variation.nonlinearClickThroughURLTemplate, this.clickTrackingURLTemplates = this.variation.nonlinearClickTrackingURLTemplates, this.setDuration(this.variation.minSuggestedDuration)) : function(e) {
        return e.adType === "companionAd";
      }(this.variation) && (this.clickThroughURLTemplate = this.variation.companionClickThroughURLTemplate, this.clickTrackingURLTemplates = this.variation.companionClickTrackingURLTemplates);
    }
  }
  setDuration(e) {
    T.isValidTimeValue(e) ? (this.assetDuration = e, this.quartiles = { firstQuartile: Math.round(25 * this.assetDuration) / 100, midpoint: Math.round(50 * this.assetDuration) / 100, thirdQuartile: Math.round(75 * this.assetDuration) / 100 }) : this.emit("TRACKER-error", { message: "the duration provided is not valid. duration: ".concat(e) });
  }
  setProgress(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, r = !(arguments.length > 2 && arguments[2] !== void 0) || arguments[2];
    if (!T.isValidTimeValue(e) || typeof t != "object") return void this.emit("TRACKER-error", { message: "One given setProgress parameter has the wrong type. progress: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
    const s = this.skipDelay || -1;
    if (s === -1 || this.skippable || (s > e ? this.emit("skip-countdown", s - e) : (this.skippable = !0, this.emit("skip-countdown", 0))), this.assetDuration > 0) {
      const i = Math.round(e / this.assetDuration * 100), o = [];
      if (e > 0) {
        o.push("start");
        for (let n = this.lastPercentage; n < i; n++) o.push("progress-".concat(n + 1, "%"));
        o.push("progress-".concat(e));
        for (const n in this.quartiles) this.isQuartileReached(n, this.quartiles[n], e) && (o.push(n), this._alreadyTriggeredQuartiles[n] = !0);
        this.lastPercentage = i;
      }
      o.forEach((n) => {
        this.track(n, { macros: t, once: r });
      }), e < this.progress && (this.track("rewind", { macros: t }), this.trackedProgressEvents && this.trackedProgressEvents.splice(0));
    }
    this.progress = e;
  }
  isQuartileReached(e, t, r) {
    let s = !1;
    return t <= r && !this._alreadyTriggeredQuartiles[e] && (s = !0), s;
  }
  setMuted(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof e == "boolean" && typeof t == "object" ? (this.muted !== e && this.track(e ? "mute" : "unmute", { macros: t }), this.muted = e) : this.emit("TRACKER-error", { message: "One given setMuted parameter has the wrong type. muted: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
  }
  setPaused(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof e == "boolean" && typeof t == "object" ? (this.paused !== e && this.track(e ? "pause" : "resume", { macros: t }), this.paused = e) : this.emit("TRACKER-error", { message: "One given setPaused parameter has the wrong type. paused: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
  }
  setFullscreen(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof e == "boolean" && typeof t == "object" ? (this.fullscreen !== e && this.track(e ? "fullscreen" : "exitFullscreen", { macros: t }), this.fullscreen = e) : this.emit("TRACKER-error", { message: "One given setFullScreen parameter has the wrong type. fullscreen: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
  }
  setExpand(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof e == "boolean" && typeof t == "object" ? (this.expanded !== e && (this.track(e ? "expand" : "collapse", { macros: t }), this.track(e ? "playerExpand" : "playerCollapse", { macros: t })), this.expanded = e) : this.emit("TRACKER-error", { message: "One given setExpand parameter has the wrong type. expanded: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
  }
  setSkipDelay(e) {
    T.isValidTimeValue(e) ? this.skipDelay = e : this.emit("TRACKER-error", { message: "setSkipDelay parameter does not have a valid value. duration: ".concat(e) });
  }
  trackImpression() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.impressed || (this.impressed = !0, this.trackURLs(this.ad.impressionURLTemplates, e), this.track("creativeView", { macros: e })) : this.emit("TRACKER-error", { message: "trackImpression parameter has the wrong type. macros: ".concat(e) });
  }
  trackViewableImpression() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, t = arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
    typeof e == "object" ? this.track("viewable", { macros: e, once: t }) : this.emit("TRACKER-error", { message: "trackViewableImpression given macros has the wrong type. macros: ".concat(e) });
  }
  trackNotViewableImpression() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, t = arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
    typeof e == "object" ? this.track("notViewable", { macros: e, once: t }) : this.emit("TRACKER-error", { message: "trackNotViewableImpression given macros has the wrong type. macros: ".concat(e) });
  }
  trackUndeterminedImpression() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, t = arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
    typeof e == "object" ? this.track("viewUndetermined", { macros: e, once: t }) : this.emit("TRACKER-error", { message: "trackUndeterminedImpression given macros has the wrong type. macros: ".concat(e) });
  }
  error() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, t = arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
    typeof e == "object" && typeof t == "boolean" ? this.trackURLs(this.ad.errorURLTemplates, e, { isCustomCode: t }) : this.emit("TRACKER-error", { message: "One given error parameter has the wrong type. macros: ".concat(T.formatMacrosValues(e), ", isCustomCode: ").concat(t) });
  }
  errorWithCode(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
    typeof e == "string" && typeof t == "boolean" ? (this.error({ ERRORCODE: e }, t), console.log("The method errorWithCode is deprecated, please use vast tracker error method instead")) : this.emit("TRACKER-error", { message: "One given errorWithCode parameter has the wrong type. errorCode: ".concat(e, ", isCustomCode: ").concat(t) });
  }
  complete() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("complete", { macros: e }) : this.emit("TRACKER-error", { message: "complete given macros has the wrong type. macros: ".concat(e) });
  }
  notUsed() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? (this.track("notUsed", { macros: e }), this.trackingEvents = []) : this.emit("TRACKER-error", { message: "notUsed given macros has the wrong type. macros: ".concat(e) });
  }
  otherAdInteraction() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("otherAdInteraction", { macros: e }) : this.emit("TRACKER-error", { message: "otherAdInteraction given macros has the wrong type. macros: ".concat(e) });
  }
  acceptInvitation() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("acceptInvitation", { macros: e }) : this.emit("TRACKER-error", { message: "acceptInvitation given macros has the wrong type. macros: ".concat(e) });
  }
  adExpand() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("adExpand", { macros: e }) : this.emit("TRACKER-error", { message: "adExpand given macros has the wrong type. macros: ".concat(e) });
  }
  adCollapse() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("adCollapse", { macros: e }) : this.emit("TRACKER-error", { message: "adCollapse given macros has the wrong type. macros: ".concat(e) });
  }
  minimize() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("minimize", { macros: e }) : this.emit("TRACKER-error", { message: "minimize given macros has the wrong type. macros: ".concat(e) });
  }
  verificationNotExecuted(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (typeof e != "string" || typeof t != "object") return void this.emit("TRACKER-error", { message: "One given verificationNotExecuted parameter has to wrong type. vendor: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
    if (!this.ad || !this.ad.adVerifications || !this.ad.adVerifications.length) throw new Error("No adVerifications provided");
    if (!e) throw new Error("No vendor provided, unable to find associated verificationNotExecuted");
    const r = this.ad.adVerifications.find((i) => i.vendor === e);
    if (!r) throw new Error("No associated verification element found for vendor: ".concat(e));
    const s = r.trackingEvents;
    if (s && s.verificationNotExecuted) {
      const i = s.verificationNotExecuted;
      this.trackURLs(i, t), this.emit("verificationNotExecuted", { trackingURLTemplates: i });
    }
  }
  overlayViewDuration(e) {
    let t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof e == "string" && typeof t == "object" ? (t.ADPLAYHEAD = e, this.track("overlayViewDuration", { macros: t })) : this.emit("TRACKER-error", { message: "One given overlayViewDuration parameters has the wrong type. formattedDuration: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
  }
  close() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track(this.linear ? "closeLinear" : "close", { macros: e }) : this.emit("TRACKER-error", { message: "close given macros has the wrong type. macros: ".concat(e) });
  }
  skip() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("skip", { macros: e }) : this.emit("TRACKER-error", { message: "skip given macros has the wrong type. macros: ".concat(e) });
  }
  load() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    typeof e == "object" ? this.track("loaded", { macros: e }) : this.emit("TRACKER-error", { message: "load given macros has the wrong type. macros: ".concat(e) });
  }
  click() {
    let e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null, t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (e !== null && typeof e != "string" || typeof t != "object") return void this.emit("TRACKER-error", { message: "One given click parameter has the wrong type. fallbackClickThroughURL: ".concat(e, ", macros: ").concat(T.formatMacrosValues(t)) });
    this.clickTrackingURLTemplates && this.clickTrackingURLTemplates.length && this.trackURLs(this.clickTrackingURLTemplates, t);
    const r = this.clickThroughURLTemplate || e, s = { ...t };
    if (r) {
      this.progress && (s.ADPLAYHEAD = this.progressFormatted());
      const i = T.resolveURLTemplates([r], s)[0];
      this.emit("clickthrough", i);
    }
  }
  trackProgressEvents(e, t, r) {
    const s = parseFloat(e.split("-")[1]);
    Object.entries(this.trackingEvents).filter((i) => {
      let [o] = i;
      return o.startsWith("progress-");
    }).map((i) => {
      let [o, n] = i;
      return { name: o, time: parseFloat(o.split("-")[1]), urls: n };
    }).filter((i) => {
      let { time: o } = i;
      return o <= s && o > this.progress;
    }).forEach((i) => {
      let { name: o, urls: n } = i;
      !r && this.trackedProgressEvents.includes(o) || (this.emit(o, { trackingURLTemplates: n }), this.trackURLs(n, t), r ? delete this.trackingEvents[o] : this.trackedProgressEvents.push(o));
    });
  }
  track(e) {
    let { macros: t = {}, once: r = !1 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (typeof t != "object") return void this.emit("TRACKER-error", { message: "track given macros has the wrong type. macros: ".concat(t) });
    e === "closeLinear" && !this.trackingEvents[e] && this.trackingEvents.close && (e = "close"), e.startsWith("progress-") && !e.endsWith("%") && this.trackProgressEvents(e, t, r);
    const s = this.trackingEvents[e], i = this.emitAlwaysEvents.indexOf(e) > -1;
    s ? (this.emit(e, { trackingURLTemplates: s }), this.trackURLs(s, t)) : i && this.emit(e, null), r && (delete this.trackingEvents[e], i && this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e), 1));
  }
  trackURLs(e) {
    var t;
    let r = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, s = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
    const { validUrls: i, invalidUrls: o } = T.filterUrlTemplates(e);
    o.length && this.emit("TRACKER-error", { message: "Provided urls are malformed. url: ".concat(o) });
    const n = { ...r };
    this.linear && (this.creative && this.creative.mediaFiles && this.creative.mediaFiles[0] && this.creative.mediaFiles[0].fileURL && (n.ASSETURI = this.creative.mediaFiles[0].fileURL), this.progress && (n.ADPLAYHEAD = this.progressFormatted())), (t = this.creative) !== null && t !== void 0 && (t = t.universalAdIds) !== null && t !== void 0 && t.length && (n.UNIVERSALADID = this.creative.universalAdIds.map((c) => c.idRegistry.concat(" ", c.value)).join(",")), this.ad && (this.ad.sequence && (n.PODSEQUENCE = this.ad.sequence), this.ad.adType && (n.ADTYPE = this.ad.adType), this.ad.adServingId && (n.ADSERVINGID = this.ad.adServingId), this.ad.categories && this.ad.categories.length && (n.ADCATEGORIES = this.ad.categories.map((c) => c.value).join(",")), this.ad.blockedAdCategories && this.ad.blockedAdCategories.length && (n.BLOCKEDADCATEGORIES = this.ad.blockedAdCategories.map((c) => c.value).join(","))), T.track(i, n, s);
  }
  convertToTimecode(e) {
    if (!T.isValidTimeValue(e)) return "";
    const t = 1e3 * e, r = Math.floor(t / 36e5), s = Math.floor(t / 6e4 % 60), i = Math.floor(t / 1e3 % 60), o = Math.floor(t % 1e3);
    return "".concat(T.addLeadingZeros(r, 2), ":").concat(T.addLeadingZeros(s, 2), ":").concat(T.addLeadingZeros(i, 2), ".").concat(T.addLeadingZeros(o, 3));
  }
  progressFormatted() {
    return this.convertToTimecode(this.progress);
  }
}
export {
  ce as c,
  ue as u
};
