(function () {
  'use strict';

  function _arrayLikeToArray(r, a) {
    (null == a || a > r.length) && (a = r.length);
    for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
    return n;
  }
  function _arrayWithHoles(r) {
    if (Array.isArray(r)) return r;
  }
  function asyncGeneratorStep(n, t, e, r, o, a, c) {
    try {
      var i = n[a](c),
        u = i.value;
    } catch (n) {
      return void e(n);
    }
    i.done ? t(u) : Promise.resolve(u).then(r, o);
  }
  function _asyncToGenerator(n) {
    return function () {
      var t = this,
        e = arguments;
      return new Promise(function (r, o) {
        var a = n.apply(t, e);
        function _next(n) {
          asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
        }
        function _throw(n) {
          asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
        }
        _next(void 0);
      });
    };
  }
  function _defineProperty(e, r, t) {
    return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
      value: t,
      enumerable: !0,
      configurable: !0,
      writable: !0
    }) : e[r] = t, e;
  }
  function _extends() {
    return _extends = Object.assign ? Object.assign.bind() : function (n) {
      for (var e = 1; e < arguments.length; e++) {
        var t = arguments[e];
        for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
      }
      return n;
    }, _extends.apply(null, arguments);
  }
  function _iterableToArrayLimit(r, l) {
    var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
    if (null != t) {
      var e,
        n,
        i,
        u,
        a = [],
        f = !0,
        o = !1;
      try {
        if (i = (t = t.call(r)).next, 0 === l) {
          if (Object(t) !== t) return;
          f = !1;
        } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
      } catch (r) {
        o = !0, n = r;
      } finally {
        try {
          if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
        } finally {
          if (o) throw n;
        }
      }
      return a;
    }
  }
  function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  function _regeneratorRuntime() {
    _regeneratorRuntime = function () {
      return e;
    };
    var t,
      e = {},
      r = Object.prototype,
      n = r.hasOwnProperty,
      o = Object.defineProperty || function (t, e, r) {
        t[e] = r.value;
      },
      i = "function" == typeof Symbol ? Symbol : {},
      a = i.iterator || "@@iterator",
      c = i.asyncIterator || "@@asyncIterator",
      u = i.toStringTag || "@@toStringTag";
    function define(t, e, r) {
      return Object.defineProperty(t, e, {
        value: r,
        enumerable: !0,
        configurable: !0,
        writable: !0
      }), t[e];
    }
    try {
      define({}, "");
    } catch (t) {
      define = function (t, e, r) {
        return t[e] = r;
      };
    }
    function wrap(t, e, r, n) {
      var i = e && e.prototype instanceof Generator ? e : Generator,
        a = Object.create(i.prototype),
        c = new Context(n || []);
      return o(a, "_invoke", {
        value: makeInvokeMethod(t, r, c)
      }), a;
    }
    function tryCatch(t, e, r) {
      try {
        return {
          type: "normal",
          arg: t.call(e, r)
        };
      } catch (t) {
        return {
          type: "throw",
          arg: t
        };
      }
    }
    e.wrap = wrap;
    var h = "suspendedStart",
      l = "suspendedYield",
      f = "executing",
      s = "completed",
      y = {};
    function Generator() {}
    function GeneratorFunction() {}
    function GeneratorFunctionPrototype() {}
    var p = {};
    define(p, a, function () {
      return this;
    });
    var d = Object.getPrototypeOf,
      v = d && d(d(values([])));
    v && v !== r && n.call(v, a) && (p = v);
    var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
    function defineIteratorMethods(t) {
      ["next", "throw", "return"].forEach(function (e) {
        define(t, e, function (t) {
          return this._invoke(e, t);
        });
      });
    }
    function AsyncIterator(t, e) {
      function invoke(r, o, i, a) {
        var c = tryCatch(t[r], t, o);
        if ("throw" !== c.type) {
          var u = c.arg,
            h = u.value;
          return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
            invoke("next", t, i, a);
          }, function (t) {
            invoke("throw", t, i, a);
          }) : e.resolve(h).then(function (t) {
            u.value = t, i(u);
          }, function (t) {
            return invoke("throw", t, i, a);
          });
        }
        a(c.arg);
      }
      var r;
      o(this, "_invoke", {
        value: function (t, n) {
          function callInvokeWithMethodAndArg() {
            return new e(function (e, r) {
              invoke(t, n, e, r);
            });
          }
          return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
        }
      });
    }
    function makeInvokeMethod(e, r, n) {
      var o = h;
      return function (i, a) {
        if (o === f) throw Error("Generator is already running");
        if (o === s) {
          if ("throw" === i) throw a;
          return {
            value: t,
            done: !0
          };
        }
        for (n.method = i, n.arg = a;;) {
          var c = n.delegate;
          if (c) {
            var u = maybeInvokeDelegate(c, n);
            if (u) {
              if (u === y) continue;
              return u;
            }
          }
          if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
            if (o === h) throw o = s, n.arg;
            n.dispatchException(n.arg);
          } else "return" === n.method && n.abrupt("return", n.arg);
          o = f;
          var p = tryCatch(e, r, n);
          if ("normal" === p.type) {
            if (o = n.done ? s : l, p.arg === y) continue;
            return {
              value: p.arg,
              done: n.done
            };
          }
          "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
        }
      };
    }
    function maybeInvokeDelegate(e, r) {
      var n = r.method,
        o = e.iterator[n];
      if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
      var i = tryCatch(o, e.iterator, r.arg);
      if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
      var a = i.arg;
      return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
    }
    function pushTryEntry(t) {
      var e = {
        tryLoc: t[0]
      };
      1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
    }
    function resetTryEntry(t) {
      var e = t.completion || {};
      e.type = "normal", delete e.arg, t.completion = e;
    }
    function Context(t) {
      this.tryEntries = [{
        tryLoc: "root"
      }], t.forEach(pushTryEntry, this), this.reset(!0);
    }
    function values(e) {
      if (e || "" === e) {
        var r = e[a];
        if (r) return r.call(e);
        if ("function" == typeof e.next) return e;
        if (!isNaN(e.length)) {
          var o = -1,
            i = function next() {
              for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
              return next.value = t, next.done = !0, next;
            };
          return i.next = i;
        }
      }
      throw new TypeError(typeof e + " is not iterable");
    }
    return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
      value: GeneratorFunctionPrototype,
      configurable: !0
    }), o(GeneratorFunctionPrototype, "constructor", {
      value: GeneratorFunction,
      configurable: !0
    }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
      var e = "function" == typeof t && t.constructor;
      return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
    }, e.mark = function (t) {
      return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
    }, e.awrap = function (t) {
      return {
        __await: t
      };
    }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
      return this;
    }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
      void 0 === i && (i = Promise);
      var a = new AsyncIterator(wrap(t, r, n, o), i);
      return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
        return t.done ? t.value : a.next();
      });
    }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
      return this;
    }), define(g, "toString", function () {
      return "[object Generator]";
    }), e.keys = function (t) {
      var e = Object(t),
        r = [];
      for (var n in e) r.push(n);
      return r.reverse(), function next() {
        for (; r.length;) {
          var t = r.pop();
          if (t in e) return next.value = t, next.done = !1, next;
        }
        return next.done = !0, next;
      };
    }, e.values = values, Context.prototype = {
      constructor: Context,
      reset: function (e) {
        if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
      },
      stop: function () {
        this.done = !0;
        var t = this.tryEntries[0].completion;
        if ("throw" === t.type) throw t.arg;
        return this.rval;
      },
      dispatchException: function (e) {
        if (this.done) throw e;
        var r = this;
        function handle(n, o) {
          return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
        }
        for (var o = this.tryEntries.length - 1; o >= 0; --o) {
          var i = this.tryEntries[o],
            a = i.completion;
          if ("root" === i.tryLoc) return handle("end");
          if (i.tryLoc <= this.prev) {
            var c = n.call(i, "catchLoc"),
              u = n.call(i, "finallyLoc");
            if (c && u) {
              if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
              if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
            } else if (c) {
              if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
            } else {
              if (!u) throw Error("try statement without catch or finally");
              if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
            }
          }
        }
      },
      abrupt: function (t, e) {
        for (var r = this.tryEntries.length - 1; r >= 0; --r) {
          var o = this.tryEntries[r];
          if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
            var i = o;
            break;
          }
        }
        i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
        var a = i ? i.completion : {};
        return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
      },
      complete: function (t, e) {
        if ("throw" === t.type) throw t.arg;
        return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
      },
      finish: function (t) {
        for (var e = this.tryEntries.length - 1; e >= 0; --e) {
          var r = this.tryEntries[e];
          if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
        }
      },
      catch: function (t) {
        for (var e = this.tryEntries.length - 1; e >= 0; --e) {
          var r = this.tryEntries[e];
          if (r.tryLoc === t) {
            var n = r.completion;
            if ("throw" === n.type) {
              var o = n.arg;
              resetTryEntry(r);
            }
            return o;
          }
        }
        throw Error("illegal catch attempt");
      },
      delegateYield: function (e, r, n) {
        return this.delegate = {
          iterator: values(e),
          resultName: r,
          nextLoc: n
        }, "next" === this.method && (this.arg = t), y;
      }
    }, e;
  }
  function _slicedToArray(r, e) {
    return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  }
  function _toPrimitive(t, r) {
    if ("object" != typeof t || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
      var i = e.call(t, r || "default");
      if ("object" != typeof i) return i;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
  }
  function _toPropertyKey(t) {
    var i = _toPrimitive(t, "string");
    return "symbol" == typeof i ? i : i + "";
  }
  function _unsupportedIterableToArray(r, a) {
    if (r) {
      if ("string" == typeof r) return _arrayLikeToArray(r, a);
      var t = {}.toString.call(r).slice(8, -1);
      return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
    }
  }

  var getFrameDepth = function getFrameDepth(win) {
    win = win || window;
    if (win === win.top) {
      return 0;
    }
    return 1 + getFrameDepth(win.parent);
  };
  var getTopAncestorOrigin = function getTopAncestorOrigin(win) {
    win = win || window;
    var ancestorOrigins = win.location && win.location.ancestorOrigins;
    if (win && ancestorOrigins && ancestorOrigins.length > 1) {
      if (Array.isArray(ancestorOrigins)) {
        return ancestorOrigins.pop();
      }
      return ancestorOrigins.item(ancestorOrigins.length - 1);
    }
    return null;
  };
  var getCanonicalUrl = function getCanonicalUrl(win) {
    win = win || window;
    var canonicalUrlLink = win.document.querySelector('link[rel=canonical]');
    return canonicalUrlLink ? canonicalUrlLink.href : null;
  };
  var findBestUrl = function findBestUrl(frameDepth, win) {
    win = win || window;
    var doc = win.document;
    if (typeof frameDepth !== 'number' || frameDepth < 0) {
      frameDepth = getFrameDepth(win);
    }
    if (frameDepth === 0) {
      return getCanonicalUrl(win) || doc.location.href;
    } else if (frameDepth === 1) {
      try {
        var parentHref = win.parent.document.location.href;
        if (parentHref) {
          return parentHref;
        }
      } catch (ex) {
        var referrer = doc.referrer;
        if (referrer) {
          return referrer;
        }
      }
    } else if (frameDepth === 2) {
      try {
        var parentReferrer = win.parent.document.referrer;
        if (parentReferrer) {
          return parentReferrer;
        }
      } catch (ex) {}
    }
    return getTopAncestorOrigin(win) || '';
  };

  function discover() {
    var win = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
    var frameDepth = arguments.length > 1 ? arguments[1] : undefined;
    var doc = win.document;
    var isPresent = win.dtm_config;
    var config1;
    if (isPresent) {
      config1 = _extends({}, win.dtm_config);
      Object.keys(config1).forEach(function (k) {
        return (config1["".concat(k)] === null || config1["".concat(k)] === '') && delete config1["".concat(k)];
      });
    } else {
      config1 = {};
    }
    config1.data_object_type_code = isPresent ? 1 : 0;
    config1.location_search = doc.location.search || '';
    config1.canonical_url = findBestUrl(frameDepth, win);
    config1.dtmc_ref = doc.referrer || '';
    config1.dtmc_loc = doc.location.href || '';
    return config1;
  }

  var getValueFromQueryString = function getValueFromQueryString(key, search) {
    if (!search) {
      return '';
    }
    var querystring = search.substring(1);
    var items = querystring.split('&');
    var filtered = items.map(function (item) {
      var itemList = item.split('=');
      return {
        key: itemList[0],
        value: itemList[1]
      };
    }).filter(function (kvp) {
      return kvp.key.toLowerCase() === key.toLowerCase();
    });
    if (filtered.length) {
      return filtered[0].value;
    }
    return '';
  };
  var serializeDataToQuery = function serializeDataToQuery(dataObject) {
    var keyFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var parts = [],
      key,
      value;
    for (key in dataObject) {
      if (keyFilter.includes(key)) {
        continue;
      } else if (dataObject.hasOwnProperty(key)) {
        value = dataObject["".concat(key)] + '' || '';
        parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
      }
    }
    return parts.join('&');
  };
  var buildUrlForPlugin = function buildUrlForPlugin(pluginName, hostName, path, dtmConfig, integration) {
    var plugin = integration.plugins["".concat(pluginName)];
    if (!plugin) {
      console.error('Missing plugin name');
      return null;
    }
    var queryStringObj = {};
    var fieldMasks = integration.fieldMasks.concat(plugin.fieldMasks);
    _extends(queryStringObj, dtmConfig);
    fieldMasks.forEach(function (fieldMask) {
      delete queryStringObj["".concat(fieldMask)];
    });
    var env = integration.env;
    var pluginUrl = "".concat(env.tagProto, "://").concat(hostName).concat(path);
    queryStringObj.dtm_cookies_enabled = navigator.cookieEnabled;
    if (env.epsilonRP) {
      queryStringObj.dtm_ept = 'final';
    }
    var keyFilter = [];
    var queryStrings = serializeDataToQuery(queryStringObj, keyFilter);
    return "".concat(pluginUrl).concat(queryStrings.length ? '?' : '').concat(queryStrings);
  };

  var applyStaticParameters = function applyStaticParameters(dtmConfig, overrideParams) {
    _extends(dtmConfig, overrideParams);
  };
  var resolve = function resolve(path, obj, separator) {
    obj = obj || self;
    separator = separator || '.';
    var properties = Array.isArray(path) ? path : path.split(separator);
    var value = properties.reduce(function (prev, curr) {
      return prev && prev[curr];
    }, obj);
    if (value === null || value === undefined) {
      return '';
    }
    return value;
  };
  var resolveForType = function resolveForType(mapping, dtmConfig) {
    if (mapping.type.toUpperCase() === 'QUERYSTRING') {
      var keys = mapping.source.split('.');
      if (keys.length === 2) {
        var sourceName = keys[0];
        return resolve(sourceName, dtmConfig);
      }
      return '';
    } else if (mapping.type.toUpperCase() === 'URLENCODE') {
      return resolve(mapping.source, dtmConfig);
    } else if (mapping.type.toUpperCase() === 'JSONURLENCODE') {
      return resolve(mapping.source, dtmConfig);
    }
    return resolve(mapping.source, dtmConfig);
  };
  var isObjectOrArray = function isObjectOrArray(value) {
    return typeof value === 'object' && value !== null;
  };
  var isPrimitive = function isPrimitive(value) {
    return value === null || typeof value !== 'object' && typeof value !== 'function';
  };
  var getJsonUrlEncodedValue = function getJsonUrlEncodedValue(str) {
    if (isPrimitive(str)) {
      return str;
    } else if (isObjectOrArray(str)) {
      return JSON.stringify(str);
    }
  };
  var transform = function transform(dtmConfig, mapping) {
    var value = resolveForType(mapping, dtmConfig);
    if (mapping.type.toUpperCase() === 'QUERYSTRING') {
      var keys = mapping.source.split('.');
      if (keys.length === 2) {
        var queryStringName = keys[1];
        var qsValue = getValueFromQueryString(queryStringName, value);
        if (qsValue !== '') {
          dtmConfig[mapping.destination] = qsValue;
        }
      }
    } else if (mapping.type.toUpperCase() === 'URLENCODE') {
      var encodedValue = encodeURIComponent(value);
      if (encodedValue !== '') {
        dtmConfig[mapping.destination] = encodedValue;
      }
    } else if (mapping.type.toUpperCase() === 'JSONURLENCODE') {
      if (value !== '') {
        var result = getJsonUrlEncodedValue(value);
        dtmConfig[mapping.destination] = result;
      }
    } else {
      if (value !== '') {
        dtmConfig[mapping.destination] = value;
      }
    }
  };
  var applyMappings = function applyMappings(dtmConfig, mappings) {
    mappings.forEach(function (m) {
      return transform(dtmConfig, m);
    });
  };

  function assign (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        target[key] = source[key];
      }
    }
    return target
  }
  var defaultConverter = {
    read: function (value) {
      if (value[0] === '"') {
        value = value.slice(1, -1);
      }
      return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
    },
    write: function (value) {
      return encodeURIComponent(value).replace(
        /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
        decodeURIComponent
      )
    }
  };
  function init (converter, defaultAttributes) {
    function set (name, value, attributes) {
      if (typeof document === 'undefined') {
        return
      }
      attributes = assign({}, defaultAttributes, attributes);
      if (typeof attributes.expires === 'number') {
        attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
      }
      if (attributes.expires) {
        attributes.expires = attributes.expires.toUTCString();
      }
      name = encodeURIComponent(name)
        .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)
        .replace(/[()]/g, escape);
      var stringifiedAttributes = '';
      for (var attributeName in attributes) {
        if (!attributes[attributeName]) {
          continue
        }
        stringifiedAttributes += '; ' + attributeName;
        if (attributes[attributeName] === true) {
          continue
        }
        stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
      }
      return (document.cookie =
        name + '=' + converter.write(value, name) + stringifiedAttributes)
    }
    function get (name) {
      if (typeof document === 'undefined' || (arguments.length && !name)) {
        return
      }
      var cookies = document.cookie ? document.cookie.split('; ') : [];
      var jar = {};
      for (var i = 0; i < cookies.length; i++) {
        var parts = cookies[i].split('=');
        var value = parts.slice(1).join('=');
        try {
          var found = decodeURIComponent(parts[0]);
          jar[found] = converter.read(value, found);
          if (name === found) {
            break
          }
        } catch (e) {}
      }
      return name ? jar[name] : jar
    }
    return Object.create(
      {
        set,
        get,
        remove: function (name, attributes) {
          set(
            name,
            '',
            assign({}, attributes, {
              expires: -1
            })
          );
        },
        withAttributes: function (attributes) {
          return init(this.converter, assign({}, this.attributes, attributes))
        },
        withConverter: function (converter) {
          return init(assign({}, this.converter, converter), this.attributes)
        }
      },
      {
        attributes: { value: Object.freeze(defaultAttributes) },
        converter: { value: Object.freeze(converter) }
      }
    )
  }
  var api = init(defaultConverter, { path: '/' });

  var daysIn13Months = 395;
  var secondsPerDay = 24 * 60 * 60;
  var millisecondsPerSecond = 1000;
  var gppTimeoutMs = 1000;
  var PATH_PREFIX = '/profile/visit/';
  var EXP_SUFFIX = '_exp';
  var EventType = {
    DISCO: 'disco',
    FINAL: 'final'
  };
  var Parameters = {
    CLEAR_TAG_FLAG: 'clear_tag_flag'
  };
  var DTM_TOKEN = 'dtm_token';
  var DTM_TOKEN_ASSIGNMENT_TYPE = 'dtm_token_assignment_type';
  var INIT_WL_CODE = 'init_wl_code';
  var CLIENT_STORAGE = 'clientStorage';
  var SERVER_OR_DOCUMENT_ONLY = 'serverOrDocument';
  var PIXEL_TIMEOUT_MS = 'px_timeout';
  var PIXEL_LATENCIES = 'px_latencies';
  var PIXEL_ID = 'px_id';
  var PIXEL_LATENCY = 'px_latency';
  var CLASS_NAME_PREFIX = 'uid-';
  var CMPS_QUERIED = 'cmps_queried';
  var GPP_STRING = 'gpp_string';
  var GPP_CMP_ID = 'gpp_cmp_id';
  var DTM_GPP_STRING = 'dtm_gpp_string';
  var DTM_GPP_CMP_ID = 'dtm_gpp_cmp_id';
  var DTM_COOKIE_ID = 'dtm_cookie_id';
  var NAMESPACED_DTM_COOKIE_ID = 'ust:dtm_cookie_id';

  var getCookie = function getCookie(name) {
    try {
      return api.get(name) || null;
    } catch (e) {
      return null;
    }
  };
  var setCookie = function setCookie(name, value, age, domain, sameSite) {
    age = age || 5 * daysIn13Months * secondsPerDay;
    sameSite = sameSite || 'lax';
    var cookieValue;
    var cookieConfig = {
      'expires': new Date(Date.now() + age * millisecondsPerSecond),
      'sameSite': sameSite,
      secure: true,
      'path': '/'
    };
    if (domain) {
      cookieConfig.domain = domain;
    } else {
      return;
    }
    cookieValue = api.set(name, value, cookieConfig);
    return cookieValue;
  };

  function removeStorageItem(key, type) {
    type = type || 'localStorage';
    try {
      var storage = window[type];
      storage.removeItem(key + EXP_SUFFIX);
      storage.removeItem(key);
      return true;
    } catch (e) {
      console.debug(e);
      return false;
    }
  }
  function getStorageItem(key, type) {
    type = type || 'localStorage';
    var val = null;
    try {
      var storage = window[type];
      var expVal = storage.getItem(key + EXP_SUFFIX);
      if (!expVal) {
        val = storage.getItem(key);
      } else {
        var expDate = new Date(expVal);
        var isValid = expDate.getTime() - Date.now() > 0;
        if (isValid) {
          val = storage.getItem(key);
        } else {
          removeStorageItem(key);
        }
      }
    } catch (e) {
      console.debug(e);
    }
    return val;
  }
  function setStorageItem(key, val, expires, type) {
    type = type || 'localStorage';
    try {
      var storage = window[type];
      if (expires !== undefined) {
        var expStr = new Date(Date.now() + expires * millisecondsPerSecond).toUTCString();
        storage.setItem(key + EXP_SUFFIX, expStr);
      }
      storage.setItem(key, val);
    } catch (e) {
      console.debug(e);
      return false;
    }
    return true;
  }

  var isValidValue = function isValidValue(val) {
    return val !== 'undefined' && val !== undefined && val !== null && val !== '';
  };
  function getValue(key, target) {
    var serverSetCookie = getCookie("".concat(key, "_sc")) || '';
    var localStorage = getStorageItem(key, 'localStorage') || '';
    var sessionStorage = getStorageItem(key, 'sessionStorage') || '';
    var documentCookie = getCookie(key) || '';
    if (target) {
      if (isValidValue(localStorage)) {
        target[key + '_ls'] = localStorage;
      }
      if (isValidValue(sessionStorage)) {
        target[key + '_ss'] = sessionStorage;
      }
      if (isValidValue(documentCookie)) {
        target[key + '_dc'] = documentCookie;
      }
    }
    var getBestValue = function getBestValue() {
      if (isValidValue(serverSetCookie)) {
        return serverSetCookie;
      }
      if (isValidValue(localStorage)) {
        return localStorage;
      }
      if (isValidValue(documentCookie)) {
        return documentCookie;
      }
      if (isValidValue(sessionStorage)) {
        return sessionStorage;
      }
      return '';
    };
    return getBestValue();
  }
  function lookupAndLoadDtmTokenValue(key, dtmTokenAssignmentType, initWLCode, target) {
    var serverSetCookie = getCookie("".concat(key, "_sc")) || '';
    var localStorage = getStorageItem(key, 'localStorage') || '';
    var sessionStorage = getStorageItem(key, 'sessionStorage') || '';
    var documentCookie = getCookie(key) || '';
    var assignmentType = dtmTokenAssignmentType;
    if (isValidValue(serverSetCookie)) {
      target["".concat(key, "_sc")] = serverSetCookie;
    }
    if (isValidValue(documentCookie)) {
      target["".concat(key, "_dc")] = documentCookie;
      target["".concat(key)] = documentCookie;
      assignmentType = '1';
    }
    if (isValidValue(localStorage)) {
      target["".concat(key, "_ls")] = localStorage;
      assignmentType = '1';
    }
    if (isValidValue(sessionStorage)) {
      target["".concat(key, "_ss")] = sessionStorage;
      assignmentType = '1';
    }
    target[DTM_TOKEN_ASSIGNMENT_TYPE] = assignmentType;
  }
  function getValues(target, integration) {
    if (integration.persistence) {
      integration.persistence.forEach(function (entry) {
        if (entry.key === DTM_TOKEN) {
          lookupAndLoadDtmTokenValue(entry.key, target["".concat(DTM_TOKEN_ASSIGNMENT_TYPE)], integration.parameters["".concat(INIT_WL_CODE)], target);
        } else {
          var oldValue = entry.context === CLIENT_STORAGE ? getWebStorageValues(entry.key) : getValue(entry.key, target);
          var newValue = target[entry.key];
          if (!isValidValue(newValue)) {
            if (isValidValue(oldValue)) {
              target[entry.key] = oldValue;
            } else if (isValidValue(entry.value)) {
              target[entry.key] = entry.value;
            }
          }
        }
      });
    }
  }
  function setDtmTokenValue(key, value, ageInSeconds, environment, context, integration) {
    var localStorageVal = getStorageItem(key, 'localStorage') || '';
    var sessionStorageVal = getStorageItem(key, 'sessionStorage') || '';
    var documentCookieVal = getCookie(key) || '';
    if (environment.pollutedFirstPartyDtmUserTknLs) {
      setStorageItem(key, '', ageInSeconds, 'localStorage');
    }
    if (environment.pollutedFirstPartyDtmUserTknSs) {
      setStorageItem(key, '', ageInSeconds, 'sessionStorage');
    }
    if (environment.pollutedFirstPartyDtmUserTkn) {
      setCookie(key, '', ageInSeconds, environment.cookieDomain);
    }
    if (environment.lsWriteExisting) {
      if (environment.pollutedFirstPartyDtmUserTknLs) {
        setStorageItem(key, integration.parameters['dtm_token'], ageInSeconds, 'localStorage');
      } else if (isValidValue(localStorageVal)) {
        setStorageItem(key, localStorageVal, ageInSeconds, 'localStorage');
      }
      if (environment.pollutedFirstPartyDtmUserTknSs) {
        setStorageItem(key, integration.parameters['dtm_token'], ageInSeconds, 'sessionStorage');
      } else if (isValidValue(sessionStorageVal)) {
        setStorageItem(key, sessionStorageVal, ageInSeconds, 'sessionStorage');
      }
    }
    if (environment.lsWriteNew) {
      if (environment.pollutedFirstPartyDtmUserTknLs || !isValidValue(localStorageVal)) {
        setStorageItem(key, integration.parameters['dtm_token'], ageInSeconds, 'localStorage');
      }
      if (environment.pollutedFirstPartyDtmUserTknSs || !isValidValue(sessionStorageVal)) {
        setStorageItem(key, integration.parameters['dtm_token'], ageInSeconds, 'sessionStorage');
      }
    }
    if (context !== CLIENT_STORAGE) {
      if ((environment.dcWriteExisting || environment.dcWriteNew) && environment.pollutedFirstPartyDtmUserTkn) {
        setCookie(key, integration.parameters['dtm_token'], ageInSeconds, environment.cookieDomain);
      } else {
        if (environment.dcWriteExisting && isValidValue(documentCookieVal)) {
          setCookie(key, documentCookieVal, ageInSeconds, environment.cookieDomain);
        }
        if (environment.dcWriteNew && !isValidValue(documentCookieVal)) {
          setCookie(key, value, ageInSeconds, environment.cookieDomain);
        }
      }
    }
  }
  function setPersistenceValue(key, value, ageInSeconds, environment, context) {
    if (context === SERVER_OR_DOCUMENT_ONLY && !environment.fpcTagWrite) {
      var _documentCookieVal = getCookie(key) || '';
      if (environment.dcWriteNew && !isValidValue(_documentCookieVal)) {
        setCookie(key, value, ageInSeconds, environment.cookieDomain);
      }
      if (environment.dcWriteExisting && isValidValue(_documentCookieVal)) {
        setCookie(key, value, ageInSeconds, environment.cookieDomain);
      }
      return;
    }
    var localStorageVal = getStorageItem(key, 'localStorage') || '';
    var sessionStorageVal = getStorageItem(key, 'sessionStorage') || '';
    var documentCookieVal = getCookie(key) || '';
    if (environment.lsWriteNew && !isValidValue(localStorageVal)) {
      setStorageItem(key, value, ageInSeconds, 'localStorage');
    }
    if (environment.lsWriteExisting && isValidValue(localStorageVal)) {
      setStorageItem(key, value, ageInSeconds, 'localStorage');
    }
    if (environment.lsWriteNew && !isValidValue(sessionStorageVal)) {
      setStorageItem(key, value, ageInSeconds, 'sessionStorage');
    }
    if (environment.lsWriteExisting && isValidValue(sessionStorageVal)) {
      setStorageItem(key, value, ageInSeconds, 'sessionStorage');
    }
    if (context !== CLIENT_STORAGE && environment.dcWriteNew && !isValidValue(documentCookieVal)) {
      setCookie(key, value, ageInSeconds, environment.cookieDomain);
    }
    if (context !== CLIENT_STORAGE && environment.dcWriteExisting && isValidValue(documentCookieVal)) {
      setCookie(key, value, ageInSeconds, environment.cookieDomain);
    }
  }
  function getWebStorageValues(key) {
    var localStorage = getStorageItem(key, 'localStorage') || '';
    var sessionStorage = getStorageItem(key, 'sessionStorage') || '';
    if (isValidValue(localStorage)) {
      return localStorage;
    }
    if (isValidValue(sessionStorage)) {
      return sessionStorage;
    }
    return '';
  }
  function loadFallbackDtmCookieIdFromWebStorage(target) {
    if (!target[DTM_COOKIE_ID]) {
      var namespacedDtmCookieId = getWebStorageValues(NAMESPACED_DTM_COOKIE_ID);
      if (namespacedDtmCookieId) {
        target[DTM_COOKIE_ID] = namespacedDtmCookieId;
      }
    }
  }
  function setValues(target, integration) {
    var setPersistenceValueLocal = function setPersistenceValueLocal(persistenceItem) {
      if (target[persistenceItem.key]) {
        if (persistenceItem.key === DTM_TOKEN) {
          setDtmTokenValue(persistenceItem.key, target[persistenceItem.key], persistenceItem.expires * secondsPerDay, integration.env, persistenceItem.context, integration);
        } else {
          setPersistenceValue(persistenceItem.key, target[persistenceItem.key], persistenceItem.expires * secondsPerDay, integration.env, persistenceItem.context);
        }
      }
    };
    if (integration.persistence) {
      integration.persistence.forEach(setPersistenceValueLocal);
    }
  }

  var createScript = function createScript(url, nonceValue, onLoadHandler, onErrorHandler) {
    var script = document.createElement('script');
    script.src = url;
    script.nonce = nonceValue;
    script.onload = onLoadHandler;
    script.onerror = onErrorHandler;
    return script;
  };
  var firePixel = function firePixel(url, onLoadHandler, onErrorHandler, referrerPolicy) {
    var img = new Image(1, 1);
    img.className = 'cnvr-pixel';
    img.style.cssText = 'display:none';
    if (typeof onLoadHandler === 'function') {
      img.onload = onLoadHandler;
    }
    if (typeof onErrorHandler === 'function') {
      img.onerror = onErrorHandler;
    }
    if (referrerPolicy) {
      img.setAttribute('referrerPolicy', referrerPolicy);
      img.referrerPolicy = referrerPolicy;
    }
    img.src = url;
    img.alt = '';
    return img;
  };
  var firePixels = function firePixels(urls, referrerPolicy) {
    var pixelArr = [];
    urls.forEach(function (url) {
      pixelArr.push(firePixel(url, null, null, referrerPolicy));
    });
    return pixelArr;
  };
  var addScriptElements = function addScriptElements(embeddedScripts, className, clearTagFlag) {
    var addedScriptReferences = [];
    embeddedScripts.forEach(function (embeddedScript) {
      var scriptElement = document.createElement('script');
      scriptElement.setAttribute('class', "".concat(CLASS_NAME_PREFIX).concat(className));
      if (embeddedScript.attributeMap) {
        var attributeMap = embeddedScript.attributeMap;
        for (var _i = 0, _Object$entries = Object.entries(attributeMap); _i < _Object$entries.length; _i++) {
          var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
            key = _Object$entries$_i[0],
            value = _Object$entries$_i[1];
          scriptElement.setAttribute(key, value);
        }
      }
      if (embeddedScript.attributeMap && embeddedScript.attributeMap.src) {
        if (clearTagFlag) {
          scriptElement.onload = scriptElement.onerror = function () {
            this.parentNode.removeChild(this);
          };
        }
        document.head.appendChild(scriptElement);
      } else if (embeddedScript.codeSnippet) {
        scriptElement.textContent = embeddedScript.codeSnippet;
        document.head.appendChild(scriptElement);
        if (clearTagFlag) {
          document.head.removeChild(scriptElement);
        }
      }
      addedScriptReferences.push(scriptElement);
    });
    return addedScriptReferences;
  };

  var firePixelWithTimeout = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(pixelId, pixelUrl, pixelTimeoutMs, referrerPolicy) {
      return _regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            return _context.abrupt("return", new Promise(function (resolve, reject) {
              var timeout = setTimeout(function () {
                reject(pixelId);
              }, pixelTimeoutMs);
              var startTime = Date.now();
              var measureLatency = function measureLatency() {
                clearTimeout(timeout);
                var endTime = Date.now();
                var latency = endTime - startTime;
                resolve([pixelId, latency]);
              };
              firePixel(pixelUrl, measureLatency, null, referrerPolicy);
            }));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function firePixelWithTimeout(_x, _x2, _x3, _x4) {
      return _ref.apply(this, arguments);
    };
  }();
  var sendPixelLatency = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(pixelPromises, pixelTimeoutMs, successLoggerUrl) {
      var promiseResults, pixelLatencies, parameters, newUrl;
      return _regeneratorRuntime().wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            Promise.allSettled = Promise.allSettled || function (promises) {
              return Promise.all(promises.map(function (p) {
                return p.then(function (value) {
                  return {
                    status: "fulfilled",
                    value: value
                  };
                }).catch(function (reason) {
                  return {
                    status: "rejected",
                    reason: reason
                  };
                });
              }));
            };
            _context2.next = 3;
            return Promise.allSettled(pixelPromises);
          case 3:
            promiseResults = _context2.sent;
            pixelLatencies = promiseResults.map(function (result) {
              if (result.status === 'rejected') {
                return _defineProperty(_defineProperty({}, PIXEL_ID, result.reason), PIXEL_LATENCY, pixelTimeoutMs + 1);
              } else if (result.status === 'fulfilled') {
                return _defineProperty(_defineProperty({}, PIXEL_ID, result.value[0]), PIXEL_LATENCY, result.value[1]);
              }
            });
            if (successLoggerUrl) {
              parameters = _defineProperty(_defineProperty({}, PIXEL_TIMEOUT_MS, pixelTimeoutMs), PIXEL_LATENCIES, JSON.stringify(pixelLatencies));
              newUrl = "".concat(successLoggerUrl, "&").concat(serializeDataToQuery(parameters));
              firePixel(newUrl);
            }
            return _context2.abrupt("return", pixelLatencies);
          case 7:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function sendPixelLatency(_x5, _x6, _x7) {
      return _ref2.apply(this, arguments);
    };
  }();
  var fireAndMeasurePixels = function fireAndMeasurePixels(pixels, successLoggerUrl, pixelTimeoutMs, referrerPolicy) {
    var pixelPromises = [];
    for (var _i = 0, _Object$entries = Object.entries(pixels); _i < _Object$entries.length; _i++) {
      var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
        pixelId = _Object$entries$_i[0],
        pixelUrl = _Object$entries$_i[1];
      pixelPromises.push(firePixelWithTimeout(pixelId, pixelUrl, pixelTimeoutMs, referrerPolicy));
    }
    return sendPixelLatency(pixelPromises, pixelTimeoutMs, successLoggerUrl);
  };

  var createPluginScript = function createPluginScript(dtmConfig, integration) {
    var env = integration.env;
    var url = buildUrlForPlugin('cnvr', env.tagHost, env.tagPath, dtmConfig, integration);
    return createScript(url, dtmConfig.nonce);
  };
  var generateAndFireFpcPixel = function generateAndFireFpcPixel(dtmConfig, integration) {
    var env = integration.env;
    if (!env || !env.fpcTagWrite && (!env.fpcAgilityIdWrite || !dtmConfig.dtm_user_id) || !navigator.cookieEnabled) {
      return '';
    }
    var wlDomainsKey = '';
    if (dtmConfig.wl_domains_key) {
      wlDomainsKey = encodeURIComponent(dtmConfig.wl_domains_key);
    }
    var wlOverrideDomain = '';
    if (dtmConfig.wl_override || dtmConfig.dtm_wl_override) {
      if (dtmConfig.wl_override) {
        wlOverrideDomain = dtmConfig.wl_override;
      } else {
        wlOverrideDomain = dtmConfig.dtm_wl_override;
      }
    }
    var baseUrl = "".concat(env.cookieProto, "://").concat(env.cookieHost).concat(env.cookiePath, "?dtm_cid=").concat(dtmConfig.dtm_cid, "&dtm_cmagic=").concat(dtmConfig.dtm_cmagic, "&ver=2&dtm_form_uid=").concat(dtmConfig.dtm_form_uid, "&wl_domains_key=").concat(wlDomainsKey, "&wl_override=").concat(wlOverrideDomain);
    var serverPersistValues = Array.isArray(integration.persistence) ? integration.persistence.filter(function (entry) {
      return entry.context === 'server' || entry.context === SERVER_OR_DOCUMENT_ONLY;
    }) : [];
    var queryParamList = [];
    if (env.epsilonRP) {
      queryParamList.push('dtm_ept=fpcset');
    }
    serverPersistValues.forEach(function (entry) {
      var key = entry.key;
      var value = dtmConfig[key];
      if (typeof value !== 'undefined') {
        if (key === DTM_TOKEN) {
          if (typeof dtmConfig["".concat(key)] !== 'undefined') {
            queryParamList.push(DTM_TOKEN + '=' + encodeURIComponent(dtmConfig["".concat(key)]));
          }
          if (typeof dtmConfig["".concat(key, "_dc")] !== 'undefined') {
            queryParamList.push(encodeURIComponent("".concat(key, "_dc")) + '=' + encodeURIComponent(dtmConfig["".concat(key, "_dc")]));
          }
          if (typeof dtmConfig["".concat(key, "_ls")] !== 'undefined') {
            queryParamList.push(encodeURIComponent("".concat(key, "_ls")) + '=' + encodeURIComponent(dtmConfig["".concat(key, "_ls")]));
          }
          if (typeof dtmConfig["".concat(key, "_ss")] !== 'undefined') {
            queryParamList.push(encodeURIComponent("".concat(key, "_ss")) + '=' + encodeURIComponent(dtmConfig["".concat(key, "_ss")]));
          }
        } else {
          queryParamList.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
        }
      }
    });
    if (dtmConfig.dtm_fpc_enable) {
      queryParamList.push('dtm_fpc_enable=' + encodeURIComponent(dtmConfig.dtm_fpc_enable));
    }
    if (dtmConfig.dtm_host) {
      queryParamList.push('dtm_host=' + encodeURIComponent(dtmConfig.dtm_host));
    }
    var pixelUrl = queryParamList.length > 0 ? "".concat(baseUrl, "&").concat(queryParamList.join('&')) : '';
    firePixel(pixelUrl);
    return pixelUrl;
  };
  var disco = function disco(dtmConfig, integration) {
    var pluginScript = createPluginScript(dtmConfig, integration);
    document.head.appendChild(pluginScript);
    var embeddedScripts = integration.embeddedScripts;
    if (Array.isArray(embeddedScripts) && embeddedScripts.length > 0) {
      addScriptElements(embeddedScripts, integration.parameters.dtm_form_uid, integration.parameters.clear_tag_flag);
    }
  };
  var final = function final(dtmConfig, integration) {
    var referrerLimitedPixels = integration.referrerLimitedPixels;
    var nonReferrerLimitedPixels = integration.pixels;
    var embeddedScripts = integration.embeddedScripts;
    var successLoggerUrl = integration.successUrl;
    var isSuccessEndpointHit = false;
    if (integration.eventType === EventType.FINAL) {
      generateAndFireFpcPixel(dtmConfig, integration);
    }
    if (referrerLimitedPixels && Object.keys(referrerLimitedPixels).length > 0) {
      var pixelTimeoutMs = integration.pixelTimeoutMs || 1500;
      fireAndMeasurePixels(referrerLimitedPixels, successLoggerUrl, pixelTimeoutMs, 'same-origin');
      isSuccessEndpointHit = true;
    }
    if (Array.isArray(nonReferrerLimitedPixels) && nonReferrerLimitedPixels.length > 0) {
      firePixels(integration.pixels);
    }
    if (Array.isArray(embeddedScripts) && embeddedScripts.length > 0) {
      addScriptElements(embeddedScripts, integration.parameters.dtm_form_uid, integration.parameters.clear_tag_flag);
    }
    if (successLoggerUrl && !isSuccessEndpointHit) {
      firePixel(successLoggerUrl);
    }
  };
  var cnvrPlugin = {
    disco: disco,
    final: final
  };

  var plugins = {
    cnvr: cnvrPlugin
  };
  function execute(dtmConfig, integration) {
    for (var _i = 0, _Object$entries = Object.entries(integration.plugins); _i < _Object$entries.length; _i++) {
      var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
        key = _Object$entries$_i[0],
        plugin = _Object$entries$_i[1];
      var pluginState = {};
      _extends(pluginState, dtmConfig);
      applyMappings(pluginState, plugin.mappings);
      if (integration.eventType === EventType.DISCO) {
        plugins[key].disco(pluginState, integration);
      }
      if (integration.eventType === EventType.FINAL) {
        plugins[key].final(pluginState, integration);
      }
    }
  }
  function executePlugins(dtmConfig, integration) {
    integration.eventType = integration.eventType || EventType.DISCO;
    execute(dtmConfig, integration);
  }

  function deleteTag() {
    var scriptElement = document.currentScript;
    if (scriptElement && scriptElement.src.toLowerCase().includes(PATH_PREFIX)) {
      scriptElement.parentNode.removeChild(scriptElement);
    }
  }
  function cleanupScript(integration) {
    var parameters = integration.parameters;
    if (parameters) {
      if (parameters.hasOwnProperty(Parameters.CLEAR_TAG_FLAG)) {
        var clearTagFlag = parameters[Parameters.CLEAR_TAG_FLAG];
        if (clearTagFlag) {
          deleteTag();
        }
      }
    }
  }

  function executePluginsAndCleanup(dtmConfig, integration) {
    executePlugins(dtmConfig, integration);
    if (integration.env) {
      setValues(dtmConfig, integration);
    }
    cleanupScript(integration);
  }

  function decodeQueryParam(str) {
    return decodeURIComponent(str.replace(/\+/g, " "));
  }

  var GPPHandler = function GPPHandler() {
    this.gppQueried = false;
  };
  var setConfig = function setConfig(dtmConfig, pingObject, win) {
    win = win || window;
    if (pingObject && pingObject.gppString) {
      win.localStorage.setItem("".concat(DTM_GPP_STRING), pingObject.gppString);
      win.localStorage.setItem("".concat(DTM_GPP_CMP_ID), pingObject.cmpId);
      dtmConfig["".concat(GPP_STRING)] = pingObject.gppString;
      dtmConfig["".concat(GPP_CMP_ID)] = pingObject.cmpId;
    } else if (win.localStorage.getItem("".concat(DTM_GPP_STRING))) {
      dtmConfig["".concat(GPP_STRING)] = win.localStorage.getItem("".concat(DTM_GPP_STRING));
      dtmConfig["".concat(GPP_CMP_ID)] = win.localStorage.getItem("".concat(DTM_GPP_CMP_ID));
    } else {
      dtmConfig["".concat(GPP_STRING)] = '';
      dtmConfig["".concat(GPP_CMP_ID)] = '';
    }
  };
  var addGppEventListener = function addGppEventListener(dtmConfig, integration, primaryCallback, win) {
    var _this = this;
    win = win || window;
    win.__gpp('addEventListener', function (event, success) {
      if (!success) {
        return;
      }
      if (!_this.gppQueried) {
        _this.gppQueried = true;
        setConfig(dtmConfig, event.pingData, win);
        primaryCallback(dtmConfig, integration);
      } else {
        setConfig(dtmConfig, event.pingData, win);
      }
    }, {}, win);
  };
  var setGppTimeoutHandler = function setGppTimeoutHandler(dtmConfig, integration, primaryCallback, win) {
    var _this2 = this;
    win = win || window;
    setTimeout(function () {
      if (!_this2.gppQueried) {
        _this2.gppQueried = true;
        var pingObject = win.__gpp('ping', function () {}, {}, win);
        setConfig(dtmConfig, pingObject, win);
        primaryCallback(dtmConfig, integration);
      }
    }, gppTimeoutMs);
  };
  var isGppAvailable = function isGppAvailable(win) {
    win = win || window;
    return win['__gpp'] && typeof win['__gpp'] === 'function';
  };
  GPPHandler.prototype.findGppString = function (dtmConfig, integration, primaryCallback, win) {
    win = win || window;
    if (isGppAvailable(win)) {
      addGppEventListener.call(this, dtmConfig, integration, primaryCallback, win);
      setGppTimeoutHandler.call(this, dtmConfig, integration, primaryCallback, win);
    } else {
      primaryCallback(dtmConfig, integration);
    }
  };

  var REASON_BROWSER = 'browser';
  var REASON_CONFIG = 'config';
  var REASON_DATA = 'data';
  var REASON_ABSENT = 'absent';
  function readOk(value) {
    return {
      value: value,
      error: null,
      errorType: null
    };
  }
  function readFail(errorType, message) {
    return {
      value: null,
      error: message,
      errorType: errorType
    };
  }
  function normalizeToken(value) {
    return value === null || value === undefined ? '' : String(value).toLowerCase();
  }
  var BLOCKED_PATH_SEGMENTS = Object.create(null);
  BLOCKED_PATH_SEGMENTS['__proto__'] = true;
  BLOCKED_PATH_SEGMENTS.prototype = true;
  BLOCKED_PATH_SEGMENTS.constructor = true;
  function isBlockedPathSegment(segment) {
    return BLOCKED_PATH_SEGMENTS[segment] === true;
  }
  function isJsArray(value) {
    return Object.prototype.toString.call(value) === '[object Array]';
  }
  function readDataProperty(parent, propName) {
    if (isBlockedPathSegment(propName)) {
      return readFail(REASON_CONFIG, "Blocked path segment \"".concat(propName, "\""));
    }
    if (parent === null || parent === undefined) {
      return readFail(REASON_ABSENT, 'Path was not found');
    }
    if (typeof parent !== 'object' && typeof parent !== 'function') {
      return readFail(REASON_DATA, 'Path continues past a scalar value');
    }
    try {
      return readOk(parent[propName]);
    } catch (e) {
      return readFail(REASON_DATA, e.message || String(e));
    }
  }

  function isStandardJsonPath(path) {
    if (path === null || path === undefined) {
      return false;
    }
    var str = String(path);
    return str.indexOf('[') === -1 && str.indexOf(']') === -1;
  }
  function resolveStandardPath(root, path) {
    if (!path) {
      return readFail(REASON_CONFIG, 'Missing path');
    }
    if (!isStandardJsonPath(path)) {
      return readFail(REASON_CONFIG, "Invalid JSON path \"".concat(path, "\""));
    }
    if (root === null || root === undefined) {
      return readFail(REASON_ABSENT, 'Path was not found');
    }
    var normalized = path;
    while (normalized.length > 0 && normalized.charAt(0) === '/') {
      normalized = normalized.substring(1);
    }
    if (normalized === '') {
      return readFail(REASON_CONFIG, "Invalid JSON path \"".concat(path, "\""));
    }
    var segments = normalized.split('/');
    var current = root;
    for (var segIdx = 0; segIdx < segments.length; segIdx++) {
      var seg = segments[segIdx];
      if (seg === '') {
        continue;
      }
      if (current === null || current === undefined) {
        return readFail(REASON_ABSENT, 'Path was not found');
      }
      if (isJsArray(current) && /^\d+$/.test(seg)) {
        var indexRead = readDataProperty(current, seg);
        if (indexRead.error) {
          return indexRead;
        }
        current = indexRead.value;
      } else {
        var propRead = readDataProperty(current, seg);
        if (propRead.error) {
          return propRead;
        }
        current = propRead.value;
      }
    }
    if (current === null || current === undefined) {
      return readFail(REASON_ABSENT, 'Path was not found');
    }
    return readOk(current);
  }

  function parseFilterPredicatesFromBody(body) {
    var chunks = body.split(',');
    var predicates = [];
    for (var c = 0; c < chunks.length; c++) {
      var piece = chunks[c];
      if (piece === '') {
        return null;
      }
      var eqIdx = piece.indexOf('=');
      if (eqIdx === -1) {
        return null;
      }
      var matchPath = piece.substring(0, eqIdx);
      var matchValue = piece.substring(eqIdx + 1);
      if (!matchPath) {
        return null;
      }
      predicates.push({
        matchPath: matchPath,
        matchValue: matchValue
      });
    }
    if (predicates.length === 0) {
      return null;
    }
    return predicates;
  }
  function parsePathSteps(path) {
    if (!path) {
      return null;
    }
    var steps = [];
    var i = 0;
    while (i < path.length) {
      if (path.charAt(i) === '/') {
        i++;
        continue;
      }
      if (path.charAt(i) === '[') {
        var closeIdx = path.indexOf(']', i + 1);
        if (closeIdx === -1) {
          return null;
        }
        var body = path.substring(i + 1, closeIdx);
        if (body === '') {
          return null;
        }
        var predicates = parseFilterPredicatesFromBody(body);
        if (!predicates) {
          return null;
        }
        steps.push({
          type: 'filter',
          predicates: predicates
        });
        i = closeIdx + 1;
        continue;
      }
      var start = i;
      while (i < path.length && path.charAt(i) !== '/' && path.charAt(i) !== '[') {
        i++;
      }
      if (i === start) {
        return null;
      }
      steps.push({
        type: 'prop',
        name: path.substring(start, i)
      });
    }
    return steps;
  }
  function getValueBySlashPath(obj, slashPath) {
    if (!slashPath) {
      return obj;
    }
    var segments = slashPath.split('/');
    var current = obj;
    for (var j = 0; j < segments.length; j++) {
      if (segments[j] === '') {
        continue;
      }
      if (current === null || current === undefined) {
        return undefined;
      }
      var segmentRead = readDataProperty(current, segments[j]);
      if (segmentRead.error) {
        return undefined;
      }
      current = segmentRead.value;
    }
    return current;
  }
  function selectArrayEntryByFilter(array, step, prefix) {
    var predicates = step.predicates;
    for (var idx = 0; idx < array.length; idx++) {
      var entryRead = readDataProperty(array, String(idx));
      if (entryRead.error) {
        continue;
      }
      var entry = entryRead.value;
      var allMatch = true;
      for (var p = 0; p < predicates.length; p++) {
        var pred = predicates[p];
        var path = pred.matchPath;
        if (prefix) {
          path = prefix + '/' + pred.matchPath;
        }
        var fieldValue = getValueBySlashPath(entry, path);
        if (String(fieldValue) !== pred.matchValue) {
          allMatch = false;
          break;
        }
      }
      if (allMatch) {
        return entry;
      }
    }
    return undefined;
  }
  function resolveKeyValuePathSteps(root, steps) {
    var current = root;
    var s = 0;
    while (s < steps.length) {
      var step = steps[s];
      if (current === null || current === undefined) {
        return readFail(REASON_ABSENT, 'Path was not found');
      }
      if (step.type === 'prop' && isJsArray(current)) {
        var j = s;
        var prefixParts = [];
        while (j < steps.length && steps[j].type === 'prop') {
          prefixParts.push(steps[j].name);
          j++;
        }
        if (j < steps.length && steps[j].type === 'filter') {
          var prefix = prefixParts.join('/');
          current = selectArrayEntryByFilter(current, steps[j], prefix);
          if (current === undefined) {
            return readFail(REASON_ABSENT, 'No array entry matched filter');
          }
          s = j + 1;
          continue;
        }
      }
      if (step.type === 'prop') {
        var propRead = readDataProperty(current, step.name);
        if (propRead.error) {
          return propRead;
        }
        current = propRead.value;
      } else if (step.type === 'filter') {
        if (!isJsArray(current)) {
          return readFail(REASON_DATA, 'Path filter applied to non-array value');
        }
        current = selectArrayEntryByFilter(current, step, '');
        if (current === undefined) {
          return readFail(REASON_ABSENT, 'No array entry matched filter');
        }
      }
      s++;
    }
    if (current === null || current === undefined) {
      return readFail(REASON_ABSENT, 'Path was not found');
    }
    return readOk(current);
  }
  function resolveKeyValuePath(root, path) {
    if (!path) {
      return readFail(REASON_CONFIG, 'Missing path');
    }
    if (root === null || root === undefined) {
      return readFail(REASON_ABSENT, 'Path was not found');
    }
    var steps = parsePathSteps(path);
    if (steps === null) {
      return readFail(REASON_CONFIG, "Invalid JSON path \"".concat(path, "\""));
    }
    if (steps.length === 0) {
      return readFail(REASON_CONFIG, "Invalid JSON path \"".concat(path, "\""));
    }
    return resolveKeyValuePathSteps(root, steps);
  }

  var MAX_STRING_LENGTH = 2000;
  var DIAGNOSTIC_VALUE_MAX_LENGTH = 2000;
  var objectSerializeCache = null;
  function resetObjectSerializeCache() {
    objectSerializeCache = new WeakMap();
  }
  function serializeObjectForScrape(value) {
    if (objectSerializeCache === null) {
      resetObjectSerializeCache();
    }
    if (objectSerializeCache.has(value)) {
      return objectSerializeCache.get(value);
    }
    var result;
    try {
      result = {
        value: JSON.stringify(value),
        error: null
      };
    } catch (e) {
      result = {
        value: null,
        error: 'Value could not be serialized'
      };
    }
    objectSerializeCache.set(value, result);
    return result;
  }
  function normalizeValueForValidation(value) {
    if (value === null || value === undefined) {
      return {
        value: value,
        error: null
      };
    }
    if (typeof value === 'object') {
      var serialized = serializeObjectForScrape(value);
      if (serialized.error) {
        return {
          value: null,
          error: serialized.error
        };
      }
      return {
        value: serialized.value,
        error: null
      };
    }
    return {
      value: String(value),
      error: null
    };
  }
  function validateValue(value) {
    if (value === null || value === undefined) {
      return 'Value cannot be null or undefined';
    }
    if (typeof value === 'string' && value.length > MAX_STRING_LENGTH) {
      return "Value exceeds ".concat(MAX_STRING_LENGTH, " characters");
    }
    return null;
  }
  function setMappedValue(destination, value, scrapeResults, upstreamError) {
    if (upstreamError) {
      scrapeResults.errors[destination] = upstreamError.message || upstreamError;
      return {
        applied: false,
        error: upstreamError.message || upstreamError,
        errorType: upstreamError.errorType || 'javascript'
      };
    }
    var normalized = normalizeValueForValidation(value);
    if (normalized.error) {
      scrapeResults.errors[destination] = normalized.error;
      return {
        applied: false,
        error: normalized.error,
        errorType: 'validation'
      };
    }
    var validationError = validateValue(normalized.value);
    if (validationError) {
      scrapeResults.errors[destination] = validationError;
      return {
        applied: false,
        error: validationError,
        errorType: 'validation'
      };
    }
    var overwrote;
    if (Object.prototype.hasOwnProperty.call(scrapeResults.values, destination)) {
      overwrote = scrapeResults.values[destination];
    }
    delete scrapeResults.errors[destination];
    scrapeResults.values[destination] = normalized.value;
    var outcome = {
      applied: true,
      value: normalized.value
    };
    if (overwrote !== undefined) {
      outcome.overwrote = overwrote;
    }
    return outcome;
  }
  function serializeDiagnosticValue(value) {
    try {
      var serialized = JSON.stringify(value);
      if (serialized.length > DIAGNOSTIC_VALUE_MAX_LENGTH) {
        serialized = serialized.substring(0, DIAGNOSTIC_VALUE_MAX_LENGTH) + '...(truncated)';
      }
      return serialized;
    } catch (e) {
      return '(unserializable)';
    }
  }

  var MAX_REGEX_INPUT_LENGTH = 5000;
  var CONDITION_TEXT_SERIALIZE_FAILED = {
    __taggyConditionTextSerializeFailed: true
  };
  function compileScrapeRegExp(pattern, flags) {
    if (!pattern) {
      return {
        re: null,
        error: 'Missing regex pattern'
      };
    }
    try {
      return {
        re: new RegExp(pattern, flags || ''),
        error: null
      };
    } catch (e) {
      return {
        re: null,
        error: e.message || String(e)
      };
    }
  }
  function textForConditionOperator(actual) {
    if (actual === null || actual === undefined) {
      return null;
    }
    if (typeof actual === 'object') {
      var serialized = serializeObjectForScrape(actual);
      if (serialized.error) {
        return CONDITION_TEXT_SERIALIZE_FAILED;
      }
      return serialized.value;
    }
    return String(actual);
  }
  function conditionStringsEqual(actualText, expected, caseSensitive) {
    var expectedStr = String(expected);
    if (caseSensitive) {
      return actualText === expectedStr;
    }
    return actualText.toLowerCase() === expectedStr.toLowerCase();
  }
  function applyRegex(rawValue, pattern, groupIndex) {
    if (rawValue === null || rawValue === undefined) {
      return {
        value: null,
        error: 'Source value is null or undefined',
        errorType: 'validation'
      };
    }
    if (!pattern) {
      return {
        value: null,
        error: 'Missing regex pattern',
        errorType: 'regex'
      };
    }
    var text;
    if (typeof rawValue === 'object') {
      var serialized = serializeObjectForScrape(rawValue);
      if (serialized.error) {
        return {
          value: null,
          error: serialized.error,
          errorType: 'validation'
        };
      }
      text = serialized.value;
    } else {
      text = String(rawValue);
    }
    if (text.length > MAX_REGEX_INPUT_LENGTH) {
      return {
        value: null,
        error: 'Regex input exceeds maximum length',
        errorType: 'regex'
      };
    }
    var compiled = compileScrapeRegExp(pattern, '');
    if (compiled.error) {
      return {
        value: null,
        error: "Invalid regex pattern: ".concat(pattern),
        errorType: 'regex'
      };
    }
    try {
      var match = text.match(compiled.re);
      if (match) {
        var targetGroup = typeof groupIndex === 'number' ? groupIndex : 0;
        if (match[targetGroup] !== undefined) {
          return {
            value: match[targetGroup],
            error: null,
            errorType: null
          };
        }
        return {
          value: null,
          error: "Regex matched, but capture group ".concat(targetGroup, " did not exist"),
          errorType: 'regex'
        };
      }
      return {
        value: null,
        error: 'Regex pattern match failed to find a correlation',
        errorType: 'regex'
      };
    } catch (err) {
      return {
        value: null,
        error: "Invalid regex compilation error: ".concat(err.message),
        errorType: 'regex'
      };
    }
  }
  function regexMatchesFull(value, pattern, conditionDebug, caseSensitive) {
    var str = String(value === null || value === undefined ? '' : value);
    if (str.length > MAX_REGEX_INPUT_LENGTH) {
      return false;
    }
    var flags = caseSensitive === false ? 'i' : '';
    var compiled = compileScrapeRegExp(pattern, flags);
    if (compiled.error) {
      if (conditionDebug && conditionDebug.invalidRegexPatterns) {
        conditionDebug.invalidRegexPatterns.push(pattern);
      }
      return false;
    }
    try {
      var match = compiled.re.exec(str);
      return match !== null && match.index === 0 && match.index + match[0].length === str.length;
    } catch (e) {
      return false;
    }
  }

  function hasDocument() {
    return typeof document !== 'undefined' && document !== null;
  }
  function hasWindow() {
    return typeof window !== 'undefined' && window !== null;
  }
  function hasLocalStorage() {
    try {
      return hasWindow() && window.localStorage !== null && window.localStorage !== undefined;
    } catch (e) {
      return false;
    }
  }
  function getCookieValue(name) {
    if (!name || !hasDocument()) {
      return null;
    }
    try {
      var parts = String(document.cookie).split(';');
      for (var i = 0; i < parts.length; i++) {
        var eqIdx = parts[i].indexOf('=');
        if (eqIdx === -1) {
          continue;
        }
        if (parts[i].substring(0, eqIdx).trim() === name) {
          return decodeURIComponent(parts[i].substring(eqIdx + 1));
        }
      }
      return null;
    } catch (e) {
      return null;
    }
  }
  function splitKeyAndSubpath(key) {
    var normalized = key;
    while (normalized.length > 0 && normalized.charAt(0) === '/') {
      normalized = normalized.substring(1);
    }
    var slashIdx = normalized.indexOf('/');
    if (slashIdx === -1) {
      return {
        rootKey: normalized,
        subPath: null
      };
    }
    return {
      rootKey: normalized.substring(0, slashIdx),
      subPath: normalized.substring(slashIdx + 1)
    };
  }
  function readCookieSegment(key, resolve) {
    if (!key) {
      return readFail(REASON_CONFIG, 'Missing cookie key');
    }
    if (!hasDocument()) {
      return readFail(REASON_BROWSER, 'document.cookie is not available in this context');
    }
    var keyParts = splitKeyAndSubpath(key);
    var cookieName = keyParts.rootKey;
    var path = keyParts.subPath;
    if (!path) {
      var _raw = getCookieValue(cookieName);
      if (_raw === null) {
        return readFail(REASON_ABSENT, "Cookie \"".concat(cookieName, "\" was not found"));
      }
      return readOk(_raw);
    }
    var raw = getCookieValue(cookieName);
    if (raw === null) {
      return readFail(REASON_ABSENT, "Cookie \"".concat(cookieName, "\" was not found"));
    }
    try {
      var parsed = JSON.parse(raw);
      var resolved = resolve(parsed, path);
      if (resolved.error) {
        return readFail(resolved.errorType, "".concat(resolved.error, " in cookie \"").concat(cookieName, "\""));
      }
      return readOk(resolved.value);
    } catch (e) {
      return readFail(REASON_DATA, "Cookie \"".concat(cookieName, "\" contains malformed JSON"));
    }
  }
  function readLocalStorageSegment(key, resolve) {
    if (!key) {
      return readFail(REASON_CONFIG, 'Missing LocalStorage key');
    }
    if (!hasLocalStorage()) {
      return readFail(REASON_BROWSER, 'localStorage is not available in this context');
    }
    var keyParts = splitKeyAndSubpath(key);
    var storageKey = keyParts.rootKey;
    var subPath = keyParts.subPath;
    var raw;
    try {
      raw = window.localStorage.getItem(storageKey);
    } catch (e) {
      return readFail(REASON_BROWSER, 'localStorage access was denied');
    }
    if (!subPath) {
      if (raw === null) {
        return readFail(REASON_ABSENT, "LocalStorage key \"".concat(storageKey, "\" was not found"));
      }
      return readOk(raw);
    }
    if (raw === null) {
      return readFail(REASON_ABSENT, "LocalStorage key \"".concat(storageKey, "\" was not found"));
    }
    try {
      var parsed = JSON.parse(raw);
      var resolved = resolve(parsed, subPath);
      if (resolved.error) {
        return readFail(resolved.errorType, "".concat(resolved.error, " in LocalStorage key \"").concat(storageKey, "\""));
      }
      var current = resolved.value;
      return readOk(current);
    } catch (e) {
      return readFail(REASON_DATA, "LocalStorage key \"".concat(storageKey, "\" contains malformed JSON"));
    }
  }
  function readCssElementValue(selector) {
    if (!selector) {
      return readFail(REASON_CONFIG, 'Missing CSS selector');
    }
    if (!hasDocument()) {
      return readFail(REASON_BROWSER, 'document is not available in this context');
    }
    var el;
    try {
      el = document.querySelector(selector);
    } catch (e) {
      return readFail(REASON_CONFIG, "Invalid CSS selector: ".concat(selector));
    }
    if (!el) {
      return readFail(REASON_ABSENT, "No element matched selector \"".concat(selector, "\""));
    }
    return readOk(el.textContent ? el.textContent.trim() : '');
  }
  function readGlobalVarSegment(key, resolve) {
    if (!key) {
      return readFail(REASON_CONFIG, 'Missing GlobalVar path');
    }
    if (!hasWindow()) {
      return readFail(REASON_BROWSER, 'window is not available in this context');
    }
    var resolved = resolve(window, key);
    if (resolved.error) {
      if (resolved.errorType === REASON_CONFIG) {
        return resolved;
      }
      return readFail(resolved.errorType, "GlobalVar path \"".concat(key, "\" was not found: ").concat(resolved.error));
    }
    return readOk(resolved.value);
  }
  function readSegmentValue(segment, key, resolve) {
    var segmentName = normalizeToken(segment);
    if (!segmentName) {
      return readFail(REASON_CONFIG, 'Missing sourceSegment');
    }
    if (segmentName === 'static') {
      return readOk(key);
    }
    if (segmentName === 'cookie') {
      return readCookieSegment(key, resolve);
    }
    if (segmentName === 'localstorage') {
      return readLocalStorageSegment(key, resolve);
    }
    if (segmentName === 'globalvar') {
      return readGlobalVarSegment(key, resolve);
    }
    if (segmentName === 'csselement') {
      return readCssElementValue(key);
    }
    return readFail(REASON_CONFIG, "Unknown sourceSegment \"".concat(segment, "\""));
  }
  function readSegmentValueSafe(segment, key, resolve) {
    try {
      return readSegmentValue(segment, key, resolve);
    } catch (error) {
      return {
        value: null,
        error: error.message || String(error),
        errorType: 'javascript'
      };
    }
  }
  function readTagUrlConfigValue(dtmConfig, sourceKey) {
    if (!sourceKey) {
      return readFail(REASON_CONFIG, 'Missing TagUrl key');
    }
    if (dtmConfig === null || dtmConfig === undefined) {
      return readFail(REASON_ABSENT, 'dtmConfig is not available for TagUrl condition');
    }
    if (!Object.prototype.hasOwnProperty.call(dtmConfig, sourceKey)) {
      return readFail(REASON_ABSENT, "TagUrl key \"".concat(sourceKey, "\" was not found"));
    }
    return readOk(dtmConfig[sourceKey]);
  }

  var CONDITION_READ_FAILED = {
    __taggyConditionReadFailed: true
  };
  function isBlank(value) {
    return value === null || value === undefined || String(value).trim() === '';
  }
  function recordConditionReadError(conditionDebug, sourceSegment, sourceKey, readResult) {
    if (!conditionDebug || !conditionDebug.readErrors || !readResult.error) {
      return;
    }
    conditionDebug.readErrors.push({
      sourceSegment: sourceSegment,
      sourceKey: sourceKey,
      errorType: readResult.errorType,
      error: readResult.error
    });
  }
  function readConditionSourceValue(node, conditionDebug, dtmConfig) {
    var sourceKey = node.sourceKey || '';
    var segmentName = normalizeToken(node.sourceSegment);
    if (segmentName === 'tagurl') {
      var _readResult = readTagUrlConfigValue(dtmConfig, sourceKey);
      if (_readResult.error) {
        recordConditionReadError(conditionDebug, node.sourceSegment, sourceKey, _readResult);
        return CONDITION_READ_FAILED;
      }
      return _readResult.value;
    }
    var pathResolve = resolveStandardPath;
    if (segmentName === 'globalvar' || segmentName === 'cookie' || segmentName === 'localstorage') {
      pathResolve = isStandardJsonPath(sourceKey) ? resolveStandardPath : resolveKeyValuePath;
    }
    var readResult = readSegmentValueSafe(node.sourceSegment, sourceKey, pathResolve);
    if (readResult.error) {
      recordConditionReadError(conditionDebug, node.sourceSegment, sourceKey, readResult);
      return CONDITION_READ_FAILED;
    }
    return readResult.value;
  }
  function evaluateConditionNode(node, conditionDebug, dtmConfig) {
    if (!node || !node.type) {
      return false;
    }
    var type = normalizeToken(node.type);
    var caseSensitive = node.caseSensitive !== false;
    if (type === 'and') {
      var branches = node.branches || [];
      if (branches.length === 0) {
        return true;
      }
      return branches.every(function (branch) {
        return evaluateConditionNode(branch, conditionDebug, dtmConfig);
      });
    }
    if (type === 'or') {
      var _branches = node.branches || [];
      if (_branches.length === 0) {
        return false;
      }
      return _branches.some(function (branch) {
        return evaluateConditionNode(branch, conditionDebug, dtmConfig);
      });
    }
    var actual = readConditionSourceValue(node, conditionDebug, dtmConfig);
    if (actual === CONDITION_READ_FAILED) {
      return false;
    }
    var args = node.args || [];
    if (type === 'is_blank') {
      return isBlank(actual);
    }
    if (type === 'is_not_blank') {
      return !isBlank(actual);
    }
    if (type === 'matches') {
      if (actual === null || actual === undefined) {
        return false;
      }
      var actualText = textForConditionOperator(actual);
      if (actualText === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      for (var i = 0; i < args.length; i++) {
        if (conditionStringsEqual(actualText, args[i], caseSensitive)) {
          return true;
        }
      }
      return false;
    }
    if (type === 'not_matches') {
      if (actual === null || actual === undefined) {
        return true;
      }
      var _actualText = textForConditionOperator(actual);
      if (_actualText === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      for (var _i = 0; _i < args.length; _i++) {
        if (conditionStringsEqual(_actualText, args[_i], caseSensitive)) {
          return false;
        }
      }
      return true;
    }
    if (type === 'contains') {
      if (actual === null || actual === undefined) {
        return false;
      }
      var _actualText2 = textForConditionOperator(actual);
      if (_actualText2 === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      for (var _i2 = 0; _i2 < args.length; _i2++) {
        var expected = String(args[_i2]);
        if (caseSensitive ? _actualText2.indexOf(expected) >= 0 : _actualText2.toLowerCase().indexOf(expected.toLowerCase()) >= 0) {
          return true;
        }
      }
      return false;
    }
    if (type === 'not_contains') {
      if (actual === null || actual === undefined) {
        return true;
      }
      var _actualText3 = textForConditionOperator(actual);
      if (_actualText3 === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      for (var _i3 = 0; _i3 < args.length; _i3++) {
        var _expected = String(args[_i3]);
        if (caseSensitive ? _actualText3.indexOf(_expected) >= 0 : _actualText3.toLowerCase().indexOf(_expected.toLowerCase()) >= 0) {
          return false;
        }
      }
      return true;
    }
    if (type === 'regex') {
      if (!args.length) {
        return false;
      }
      var _actualText4 = textForConditionOperator(actual);
      if (_actualText4 === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      var value = _actualText4 === null ? '' : _actualText4;
      return regexMatchesFull(value, args[0], conditionDebug, caseSensitive);
    }
    if (type === 'like') {
      var _actualText5 = textForConditionOperator(actual);
      if (_actualText5 === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      var _value = _actualText5 === null ? '' : _actualText5;
      for (var _i4 = 0; _i4 < args.length; _i4++) {
        if (regexMatchesFull(_value, args[_i4], conditionDebug, caseSensitive)) {
          return true;
        }
      }
      return false;
    }
    if (type === 'is_not_like') {
      var _actualText6 = textForConditionOperator(actual);
      if (_actualText6 === CONDITION_TEXT_SERIALIZE_FAILED) {
        return false;
      }
      var _value2 = _actualText6 === null ? '' : _actualText6;
      for (var _i5 = 0; _i5 < args.length; _i5++) {
        if (regexMatchesFull(_value2, args[_i5], conditionDebug, caseSensitive)) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  function isRegDebugEnabled(dtmConfig) {
    if (!dtmConfig) {
      return false;
    }
    var flag = dtmConfig.dtm_reg_debug;
    return flag === true || flag === 'true' || flag === '1';
  }
  function serializeForDiagnostic(obj) {
    try {
      return JSON.stringify(obj);
    } catch (e) {
      return String(obj);
    }
  }
  function validateMappingType(mappingType, segmentName) {
    if (mappingType === 'static') {
      if (segmentName !== 'static') {
        return 'Mapping type "static" requires sourceSegment "Static"';
      }
      return null;
    }
    if (mappingType === 'jsonmapelement') {
      if (segmentName !== 'globalvar' && segmentName !== 'cookie' && segmentName !== 'localstorage') {
        return 'Mapping type "JsonMapElement" requires sourceSegment GlobalVar, Cookie, or LocalStorage';
      }
      return null;
    }
    if (mappingType === 'name' || mappingType === 'regex') {
      return null;
    }
    return "Unknown mapping type \"".concat(mappingType, "\"");
  }
  function isTransformationActive(transformation) {
    if (transformation.paused === true) {
      return false;
    }
    if (transformation.status && String(transformation.status).toUpperCase() !== 'ACTIVE') {
      return false;
    }
    return true;
  }
  function buildMappingDiagnosticEntry(mapping, outcome) {
    var entry = {
      mapping: serializeForDiagnostic(mapping),
      destination: mapping && mapping.destination ? mapping.destination : undefined
    };
    if (outcome.applied) {
      entry.status = 'applied';
      entry.value = serializeDiagnosticValue(outcome.value);
      if (outcome.overwrote !== undefined) {
        entry.overwrote = serializeDiagnosticValue(outcome.overwrote);
      }
    } else if (outcome.skipped) {
      entry.status = 'skipped';
    } else {
      entry.status = 'error';
      entry.errorType = outcome.errorType || 'javascript';
      entry.error = outcome.error;
    }
    return entry;
  }
  function applyReadFailure(destination, readResult, scrapeResults, recordOutcome) {
    scrapeResults.errors[destination] = readResult.error;
    recordOutcome({
      applied: false,
      error: readResult.error,
      errorType: readResult.errorType || REASON_BROWSER
    });
  }
  function applyMappingConfigFailure(destination, message, scrapeResults, recordOutcome) {
    scrapeResults.errors[destination] = message;
    recordOutcome({
      applied: false,
      error: message,
      errorType: 'config'
    });
  }
  function applyMapping(mapping, scrapeResults, mappingDiagnostics) {
    if (!mapping || !mapping.destination) {
      return;
    }
    var destination = mapping.destination;
    var recordOutcome = function recordOutcome(outcome) {
      if (mappingDiagnostics) {
        mappingDiagnostics.push(buildMappingDiagnosticEntry(mapping, outcome));
      }
    };
    try {
      var mappingType = mapping.type ? normalizeToken(mapping.type) : 'name';
      var segmentName = normalizeToken(mapping.sourceSegment);
      var typeError = validateMappingType(mappingType, segmentName);
      if (typeError) {
        applyMappingConfigFailure(destination, typeError, scrapeResults, recordOutcome);
        return;
      }
      if (mappingType === 'static') {
        var _outcome = setMappedValue(destination, mapping.source, scrapeResults, null);
        recordOutcome(_outcome);
        return;
      }
      var pathResolve = mappingType === 'jsonmapelement' ? resolveKeyValuePath : resolveStandardPath;
      var readResult = readSegmentValueSafe(mapping.sourceSegment, mapping.source, pathResolve);
      if (readResult.error) {
        applyReadFailure(destination, readResult, scrapeResults, recordOutcome);
        return;
      }
      var rawValue = readResult.value;
      if (mappingType === 'regex') {
        var pattern = mapping.regex && mapping.regex.pattern;
        var groupIndex = mapping.regex && typeof mapping.regex.group === 'number' ? mapping.regex.group : 0;
        var regexResult = applyRegex(rawValue, pattern, groupIndex);
        if (regexResult.error) {
          scrapeResults.errors[destination] = regexResult.error;
          recordOutcome({
            applied: false,
            error: regexResult.error,
            errorType: regexResult.errorType
          });
          return;
        }
        var _outcome2 = setMappedValue(destination, regexResult.value, scrapeResults, null);
        recordOutcome(_outcome2);
        return;
      }
      var normalizedValue = rawValue === undefined ? null : rawValue;
      var outcome = setMappedValue(destination, normalizedValue, scrapeResults, null);
      recordOutcome(outcome);
    } catch (error) {
      var message = "Fatal unexpected engine crash: ".concat(error.message);
      scrapeResults.errors[destination] = message;
      recordOutcome({
        applied: false,
        error: message,
        errorType: 'javascript'
      });
    }
  }
  function normalizeScrapeConfig(scrapeConfig) {
    var parsed = scrapeConfig;
    if (typeof scrapeConfig === 'string') {
      try {
        parsed = JSON.parse(scrapeConfig);
      } catch (e) {
        return null;
      }
    }
    if (!Array.isArray(parsed) || parsed.length === 0) {
      return null;
    }
    return parsed;
  }
  function processTransformation(transformation, scrapeResults, regDebug, dtmConfig) {
    var mappingDiagnostics = regDebug ? [] : null;
    var diagEntry = regDebug ? {
      transformationId: transformation.id,
      transformationName: transformation.name,
      skipped: false,
      mappings: mappingDiagnostics
    } : null;
    if (!isTransformationActive(transformation)) {
      if (diagEntry) {
        diagEntry.skipped = true;
        diagEntry.skipReason = 'Transformation is paused or not ACTIVE';
        diagEntry.condition = transformation.conditionTree ? serializeForDiagnostic(transformation.conditionTree) : 'none';
        scrapeResults.diagnostics.push(diagEntry);
      }
      return;
    }
    var tree = transformation.conditionTree;
    var mappings = tree && tree.taggingMappingsList ? tree.taggingMappingsList : [];
    if (!mappings.length) {
      if (diagEntry) {
        diagEntry.condition = tree ? serializeForDiagnostic(tree) : 'none';
        diagEntry.conditionResult = null;
        scrapeResults.diagnostics.push(diagEntry);
      }
      return;
    }
    var conditionDebug = regDebug ? {
      invalidRegexPatterns: [],
      readErrors: []
    } : null;
    var conditionResult = evaluateConditionNode(tree, conditionDebug, dtmConfig);
    if (diagEntry) {
      diagEntry.condition = tree ? serializeForDiagnostic(tree) : 'none';
      diagEntry.conditionResult = conditionResult;
      if (conditionDebug && conditionDebug.invalidRegexPatterns.length) {
        diagEntry.conditionInvalidRegexPatterns = conditionDebug.invalidRegexPatterns.slice();
      }
      if (conditionDebug && conditionDebug.readErrors.length) {
        diagEntry.conditionReadErrors = conditionDebug.readErrors.slice();
      }
    }
    if (!conditionResult) {
      if (diagEntry) {
        scrapeResults.diagnostics.push(diagEntry);
      }
      return;
    }
    mappings.forEach(function (mapping) {
      applyMapping(mapping, scrapeResults, mappingDiagnostics);
    });
    if (diagEntry) {
      scrapeResults.diagnostics.push(diagEntry);
    }
  }
  function evaluateBrowserTransformations(transformations, scrapeResults, dtmConfig) {
    resetObjectSerializeCache();
    if (dtmConfig === null || dtmConfig === undefined) {
      dtmConfig = {};
    }
    var regDebug = isRegDebugEnabled(dtmConfig);
    if (regDebug && !scrapeResults.diagnostics) {
      scrapeResults.diagnostics = [];
    }
    transformations.forEach(function (transformation) {
      try {
        processTransformation(transformation, scrapeResults, regDebug, dtmConfig);
      } catch (error) {
        if (regDebug) {
          scrapeResults.diagnostics.push({
            transformationId: transformation.id,
            transformationName: transformation.name,
            skipped: false,
            errorType: 'javascript',
            transformationError: error.message || String(error),
            mappings: []
          });
        }
      }
    });
  }
  function mergeScrapeValues(dtmConfig, scrapeResults) {
    if (!scrapeResults || !scrapeResults.values) {
      return;
    }
    Object.keys(scrapeResults.values).forEach(function (key) {
      var value = scrapeResults.values[key];
      if (value !== null && value !== undefined) {
        dtmConfig[key] = value;
      }
    });
  }
  function logScrapeDiagnostics(scrapeResults, dtmConfig) {
    if (!isRegDebugEnabled(dtmConfig)) {
      return;
    }
    if (!scrapeResults || !scrapeResults.diagnostics || !scrapeResults.diagnostics.length) {
      console.log('[dtm_reg_debug] scrape diagnostics: (none)');
      return;
    }
    console.log('[dtm_reg_debug] scrape diagnostics:', serializeForDiagnostic(scrapeResults.diagnostics));
  }
  function evaluateDiscoveryScrape(scrapeConfig, dtmConfig, scrapeResults) {
    try {
      var transformations = normalizeScrapeConfig(scrapeConfig);
      if (transformations) {
        evaluateBrowserTransformations(transformations, scrapeResults, dtmConfig);
      }
    } catch (err) {} finally {
      logScrapeDiagnostics(scrapeResults, dtmConfig);
    }
  }

  var integration = {"eventType":"disco","env":{"tagProto":"https","tagHost":"login-ds.dotomi.com","tagPath":"/profile/visit/final/js","dcWriteNew":false,"dcWriteExisting":false,"lsWriteNew":false,"lsWriteExisting":false,"fpcRead":true,"fpcTagWrite":false,"fpcAgilityIdWrite":false,"cookieHost":"","cookieProto":"https","cookiePath":"","cookieDomain":"","epsilonRP":false,"pollutedFirstPartyDtmUserTkn":false,"pollutedFirstPartyDtmUserTknLs":false,"pollutedFirstPartyDtmUserTknSs":false},"parameters":{"dtm_form_uid":"402808877758099642","cmps_queried":false,"cachebuster":"1436466257","tcflag":"true","dtm_token_assignment_type":"0","dtm_cid":"80602","dtm_fid":"101","dtm_zip_code":"20147","dtm_user_dc":"iad","dtm_id_assgn_type":"0","dtm_state":"VA","dccu":"true","dtm_user_agent":"CCBot%2F2.0+%28https%3A%2F%2Fcommoncrawl.org%2Ffaq%2F%29","dtm_country_code":"US","init_wl_code":"3","ops_test_camp":"false","dtm_token":"AQAElhGLQrJm_QFBNNK7AQA72wABAQCguBIHCwEBAKC4EgcL","dtm_dma_code":"511","dtm_cmagic":"a06782","init_ts":"1794106394122","dtm_client_optout":"false","dtm_tag_complete":"false","wl_domains_key":"%5E%28.*%5C.%29%3Fdodge%5C.com%24-www.dodge.com-%2Ftag_path-","dtm_promo_id":"299","dtm_cookies_enabled":"false"},"mappings":[{"id":0,"scope":"Client","source":"dtm_promo_id","destination":"cli_promo_id","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"items","destination":"dtm_items","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"dtmc_items","destination":"dtm_items","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"dtm_items","destination":"dtm_items","type":"JSONURLENCODE","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"coupons","destination":"dtmc_coupons","type":"JSONURLENCODE","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"bypass_channel","destination":"dtmc_bypass_channel","type":"JSONURLENCODE","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"dtmc_tf_loc","destination":"dtmc_loc","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false}],"persistence":[{"key":"dtm_status","expires":395.0,"noSuffix":false},{"key":"dtm_token","expires":395.0,"context":"server","noSuffix":false},{"key":"dtm_persisted_em","expires":395.0,"context":"client","noSuffix":false},{"key":"dtm_sync","expires":9.0,"context":"clientStorage","noSuffix":false},{"key":"dtm_consent","expires":395.0,"context":"client","noSuffix":false}],"fieldMasks":["location_search","coupons","items","bypassChannel"],"plugins":{"cnvr":{"name":"cnvr","parameters":{},"mappings":[{"id":0,"scope":"Client","source":"location_search.dtm_em","destination":"dtm_email_hash","type":"QUERYSTRING","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"email_hash","destination":"dtm_email_hash","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"confirmation_number","destination":"dtmc_transaction_id","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false},{"id":0,"scope":"Client","source":"dtm_promo_id","destination":"cli_promo_id","type":"NAME","paused":false,"cnvrEnabled":false,"cjEnabled":false,"index":-1,"redactOriginal":false}],"fieldMasks":["confirmation_number","email_hash"]}},"embeddedScripts":[]};
  var scrapeConfig = [];
  var discoveredDtmConfig = discover();
  var dtmConfig = {};
  var scrapeResults = {
    values: {},
    errors: {},
    diagnostics: []
  };
  if (integration.parameters) {
    var decodedParameters = {};
    Object.entries(integration.parameters).forEach(function (_ref) {
      var _ref2 = _slicedToArray(_ref, 2),
        key = _ref2[0],
        value = _ref2[1];
      try {
        decodedParameters[decodeQueryParam(key)] = decodeQueryParam(value);
      } catch (err) {}
    });
    applyStaticParameters(dtmConfig, decodedParameters);
  }
  applyStaticParameters(dtmConfig, discoveredDtmConfig);
  if (integration.env.fpcRead) {
    getValues(dtmConfig, integration);
    loadFallbackDtmCookieIdFromWebStorage(dtmConfig);
  }
  applyMappings(dtmConfig, integration.mappings);
  if (integration.eventType === EventType.DISCO) {
    try {
      evaluateDiscoveryScrape(scrapeConfig, dtmConfig, scrapeResults);
    } finally {
      mergeScrapeValues(dtmConfig, scrapeResults);
    }
  }
  if (integration.eventType === EventType.DISCO && integration.parameters && !integration.parameters.cmps_queried) {
    var gppHandler = new GPPHandler();
    dtmConfig["".concat(CMPS_QUERIED)] = true;
    gppHandler.findGppString(dtmConfig, integration, executePluginsAndCleanup);
  } else {
    executePluginsAndCleanup(dtmConfig, integration);
  }

})();
